Happy 2006 POJ - 2773 数论

题目链接


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
5

题意:

找与 m 互质的 第 k 大的数,

思路:

第一种: 暴力, 若a和b互素的话,则b*t+a和b一定互素,反之亦然,与m互素的数对m取余的话有一定的周期性规律,然后就可以直接算,假设小于m的数且与m互素的数有k个,其中第i个是ai,则第m×k+i与m互素的数是k×m+ai.

第二种:

利用欧拉函数找出与m互质的数的数目,并且筛选出与m互质的数,然后剩下的就是和暴力差不多的过程了.

代码:
第一种:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;

typedef long long LL;
const int maxn = 1e6 +10;
int a[maxn];

int gcd(int a, int b){
    return b ? gcd(b, a% b) : a;
}

int main(){
    int k, m;
    ios::sync_with_stdio(false);
    while(cin >> m >> k){
        int cnt = 0;
        k--;
        for(int  i = 1; i <= m; ++i)
            if(gcd(i, m) == 1)
                a[cnt++] = i;
       cout<<a[k % cnt] + k / cnt * m<<endl;
    }return 0;
}

第二种:

#include<cstring>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;

typedef long long LL;
const int maxn = 1e6 +10;
bool prime[maxn];

int euler(int n){
     int ans = n;
    int m = n;
    memset(prime, false, sizeof(prime));
    for(int i = 2; i * i <= n; ++i)
        if(n % i == 0){
            ans -= ans / i;
            for(int j = 1; j * i <= m; ++j)
                prime[j * i] = true;
            while(n % i == 0)
                n /= i;
        }if(n > 1){
            ans -= ans / n;
            for(int j = 1; j * n <= m; ++j)
                prime[j * n] = true;
    }return ans;
}

int main(){
    int n, k;
    ios::sync_with_stdio(false);
    while(cin >> n >> k){
        int t = euler(n);
        int tt = k / t;
        if(k % t == 0) tt--;
        int num = 0,cur;
        t = k - t * tt;
        for(int i = 1; i <= n; ++i){
            if(!prime[i])
                ++num;
            if(num == t){
                cur = i;
                break;
            }
        }cout<<cur + n * tt<<endl;
    }return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值