Happy 2006(POJ-2773)

Problem Description

Two positive integers are said to be relatively prime to each other if the Great Common Divisor (GCD) is 1. For instance, 1, 3, 5, 7, 9...are all relatively prime to 2006.

Now your job is easy: for the given integer m, find the K-th element which is relatively prime to m when these elements are sorted in ascending order.

Input 

The input contains multiple test cases. For each test case, it contains two integers m (1 <= m <= 1000000), K (1 <= K <= 100000000).

Output

Output the K-th element in a single line.

Sample Input

2006 1
2006 2
2006 3

Sample Output

1
3

题意:给出 n、k 两个数,从 2 开始,求第 k 个 n 互素的数

思路:

有这么一条性质:如果 a 与 b 互素,那么 b*t+a 肯定与 b 也互素

即:GCD(b*t+a,b)=GCD(a,b)

因此,与 n 互素的数对 n 取模具有周期性,根据这个方法可以很快的求出第 k 个与 n 互素的数

假设小于 n 的数且与 n 互素的数有 k 个,第 i 个是 ai,则第 n*k+i 与 n 互素的数是 k×n+ai

Source Program

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstdlib>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<ctime>
#include<vector>
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define N 1000005
#define MOD 1e9+7
#define E 1e-6
#define LL long long
using namespace std;
int a[N];
int GCD(int x,int y)
{
    if(y==0)
        return x;
    else
        return GCD(y,x%y);
}
int main()
{
    int n,k;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        int j=0;
        for(int i=1;i<=n;i++)
            if(GCD(n,i)==1)
                a[j++]=i;

        if(k%j)
            printf("%d\n",k/j*n+a[k%j-1]);
        else
            printf("%d\n",(k/j-1)*n+a[j-1]);
    }

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值