其他分享
首页 > 其他分享> > Happy 2006

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.

输入:

输出:

样例输入:

样例输出:

题目大意:

给你两个整数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;
 } 

标签:prime,int,互素,Happy,2006,include,互质,relatively
来源: https://blog.csdn.net/Prediction__/article/details/99996703