Happy 2006

题目描述:

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.

输入:

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

输出:

Output the K-th element in a single line.

样例输入:

2006 1
2006 2
2006 3

样例输出:

Sample Output
1
3
5

题目大意:

给你两个整数N和K,找到第k个与N互素的数(互素的数从小到大排列),其中
(1 <= m <= 1000000,1 <= K <= 100000000 )。

思路:

第一种:

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

第二种:

利用欧拉函数找出与m互质的数的数目,并且筛选出与m互质的数。

code:

这里是第一种

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int a[1000006];
int gcd(int a,int b)
{
	if(b==0)return a;
	return gcd(b,a%b);
}
int main()
{
	int n,m;
	while(~scanf("%d%d",&n,&m))
	{
		int k=0;
		for(int i=1;i<=n;i++)
		{
			if(gcd(i,n)==1)
				a[k++]=i;
		}
		if(m%k==0)
			printf("%d\n",(m/k-1)*n+a[k-1]);
		else
			printf("%d\n",(m/k)*n+a[m%k-1]);
	}
	return 0;
 } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值