思路:
找每一个数的循环节,注意优化!!
每次找一个数的循环节时,记录其路径,下次对应的数就不用再找了……
代码如下:
#include<iostream>
#include<cstdio>
#include<stack>
#include<cstring>
#define ll __int64
using namespace std;
int vis[],to[],an[];
stack<int>p;
ll gcd(ll a,ll b)
{
if(a<b) swap(a,b);
while(b){
ll t=a;
a=b;
b=t%b;
}
return a;
}
int main()
{
int i,j,n,k,a,b;
ll ans,num;
while(scanf("%d%d",&n,&k)&&(n+k)){
j=;
while(!p.empty()) p.pop();
for(i=;i<=k;i++){
a=i;
while(a<=n){
p.push(a);
a+=k;
}
while(!p.empty()){
b=p.top();
to[b]=j++;
p.pop();
}
}
memset(vis,,sizeof(vis));
ans=;
for(i=;i<=n;i++){
if(vis[i]==){
num=;
a=to[i];
while(a!=i){
vis[a]=;
a=to[a];
num++;
}
ans=num/gcd(num,ans)*ans;
}
}
printf("%I64d\n",ans);
}
return ;
}