原题:
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。 所以,加上这么个小的优化策略,就能通过数据了