cf Educational Codeforces Round 54 B. Divisor Subtraction

本文详细解析了一种求解整数n通过不断减去其最小质因子直至变为0的算法,探讨了算法的实现方式及优化策略,通过实例展示了算法的具体运行过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题:
B. Divisor Subtraction
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an integer number n. The following algorithm is applied to it:

if n=0, then end algorithm;
find the smallest prime divisor d of n;
subtract d from n and go to step 1.
Determine the number of subtrations the algorithm will make.

Input
The only line contains a single integer n (2≤n≤10^10).

Output
Print a single integer — the number of subtractions the algorithm will make.

Examples
input
5
output
1
input
4
output
2
Note
In the first example 5 is the smallest prime divisor, thus it gets subtracted right away to make a 0.

In the second example 2 is the smallest prime divisor at both steps.

中文:
给你一个数n,让你将这个数走一遍如下的算法,要求如果n等于0就结束,否则找到n的最小质因子,然后用n减去该因子。不断的重复该过程,问你这个算法会重复多少次?

代码:

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef pair<int,int> pii;

ll n;

int main()
{
    ios::sync_with_stdio(false);
    while(cin>>n)
    {
        ll ans=0,flag;
        while(n)
        {
            flag=0;
            for(ll i=2;i<=sqrt(n);i++)
            {
                if(n%i==0)
                {
                    if(i==2)
                    {
                        flag=-1;
                        ans+=n/i;
                        break;
                    }
                    n-=i;
                    ans++;
                    flag=1;
                    break;
                }
            }
            if(flag==-1)
                break;
            if(!flag)
            {
                ans++;
                break;
            }
        }
        cout<<ans<<endl;
    }

    return 0;
}

解答:

简单的使用暴力来模拟算法是会超时的,因为数据范围在101010^{10}1010当中,在纸上算一算可以发现,因为2是最小的质数,如果一个数有质因子2,那么n一定可以不停的减去2最后得到0。 所以,加上这么个小的优化策略,就能通过数据了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值