1076B Divisor Subtraction
B. Divisor Subtraction
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given an integer number nn. The following algorithm is applied to it:
- if n=0n=0, then end algorithm;
- find the smallest prime divisor dd of nn;
- subtract dd from nn and go to step 11.
Determine the number of subtrations the algorithm will make.
Input
The only line contains a single integer nn (2≤n≤10102≤n≤1010).
Output
Print a single integer — the number of subtractions the algorithm will make.
Examples
input
Copy
5
output
Copy
1
input
Copy
4
output
Copy
2
Note
In the first example 55 is the smallest prime divisor, thus it gets subtracted right away to make a 00.
In the second example 22 is the smallest prime divisor at both steps.
題意:給出一個數n,找出最小質因子,然後n-減去這個質因子,無限次這種迴圈直到n=0,求出一共需要進行多少次。
題解:我的方法是先線性篩,篩出1e5內的質因子,然後看n沒有質因子,有的話,就要分三種情況,一種是奇數減去第一次質因子後,變成偶數了,以後的質因子都是2了,不再是3,例如15,質因子為3,減去後為12,所以最終答案是7不是5。一種是:質因子就是本身的例如5,就是n/質因子,嚴格來說就是兩種,但是n的範圍很大1e10,線性篩,篩不完,所以要特判,如果在1e5內沒有質因子,就是答案就是1,(因為質因子就是本身,第二種情況)
c++:
#include<bits/stdc++.h>
using namespace std;
int vis[100000];
int a[100010],cnt;
void Init()
{
memset(vis,0,sizeof(vis));
int i,j;
for(i=2; i<100000; i++)
{
if(!vis[i])
{
a[cnt++]=i;
for(j=i+i; j<100000; j+=i)
{
vis[j]=1;
}
}
}
}
int main()
{
Init();///線性篩模版
long long n,ans=0;
cin>>n;
for(int i=0; i<cnt; i++)
if(n%a[i]==0&&(n-a[i])%2==0)
{
cout<<(n-a[i])/2+1<<endl;
return 0;
}
else if(n%a[i]==0)
{
cout<<n/a[i]<<endl;
return 0;
}
cout<<1<<endl;
return 0;
}
還有大神的簡短程式碼:c++:
#include <stdio.h>
#include <vector>
int main()
{
long long n,i,i2;
scanf("%I64d",&n);
for(i=2;i*i<=n;i++)
{
if(n%i==0)
{
printf("%I64d",1+(n-i)/2);
return 0;
}
}
printf("%d",1);
return 0;
}
python:
n=int(input())
for i in range(2,int(n**0.5)+1):
if n%i==0:
print(1+(n-i)//2)
exit()
print(1)