AtCoder Beginner Contest 161 F.Division or Subtraction
Problem Statement
Given is a positive integer N.
We will choose an integer K between 2 and N (inclusive), then we will repeat the operation below until N becomes less than K.
- Operation: if K divides N, replace N with N/K; otherwise, replace N with N−K.
In how many choices of K will N become 1 in the end?
Constraints
N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of choices of K in which N becomes 1 in the end.
Sample Input 1
6
Sample Output 1
3
Sample Input 2
3141
Sample Output 2
13
Sample Input 3
314159265358
Sample Output 3
9
对每个数
,使
变为
必有两个数
和
两个数(2除外,因为1不符合条件)
如果满足除操作,那么
一定是
的因子;如果满足减操作得到1,那么
一定是
的因子,所以可选的所有数必然在 n 的因子内,即
对数
,我们可以直接模拟上述过程判断,对
,我们可以直接用
进行判断,注意特判一下
,避免重复判断。
AC代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ll n,ans=2;
cin>>n;
if(n==2) ans=1;
for(ll k=2;k*k<=n;k++){
ll m=n;
while(m>=k) m%k?m%=k:m/=k;
if(m==1) ans++;
if((n-1)%k==0 && k*k!=(n-1)) ans++;
}
cout<<ans<<endl;
return 0;
}