# 一个超时的题，本是想用Java学调试的,写辛苦了，所以抄下来

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.

import java.util.*;
import java.math.*;

public class Main
{
static int prime[] = new int[1000];
static boolean isprime[] = new boolean[1000];
static long factor[] = new long[20];

public static void creatprime()//产生素数表
{
Arrays.fill(isprime, false);
for(int i=2;i<1000; i+= 2)
isprime[i] = true;
int k=1;
prime[0]=2;
for(int i=3;i<1000;i+=2)
{
if(!isprime[i])
{
prime[k++] = i;
for(int j=i+i;j<1000;j+=i)
isprime[j]= true;
}
}
}

public static boolean isPrime(long n)//判断是不是素数
{
for(int i= 0;prime[i]*prime[i]<=n;i++)
{
if(n%prime[i]==0) return false;
}
return true;
}

public static void factors(long n)//对一个数求它的因子，并存入factor数组
{
int k = 0;
Arrays.fill(factor,0);
for(int i=0;prime[i]<=n&&i<1000;i++)
{
if(n%prime[i]==0)
{
factor[k++] = prime[i];
while(n%prime[i]==0) n/=prime[i];
}
}
return ;

}

public static int howMany(long n)//使用队列模拟容斥原理，其实不知道正不正确
{
Queue<Long> G = new ArrayDeque<Long>();
for(int i=0;i<factor.length&&factor[i]!=0;i++)
int sum = 0;
while(!G.isEmpty())
{
long k = G.poll();
sum += n/k;
for(int i=0;i<factor.length&&factor[i]!=0;i++)
{
if(factor[i]>k)
if(Math.abs(k)%factor[i]!=0)
{
long temp = k*(-factor[i]);
}
}
}
return sum;

}

public static boolean hasFactor(long n)//数n有factor里的因子吗？
{
for(int i=0;i<factor.length && factor[i]!=0;i++)
if(n%factor[i]==0)return true;
return false;
}

public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
long k,m;

Main.creatprime();

while(in.hasNext())
{
k = in.nextLong();
m = in.nextLong();

if(m==1) System.out.println("1");//1的特殊判断
else if(Main.isPrime(k))///k如果是素数，用下面的判别
{
if(m<k)System.out.println(m);
else
{
long n = 1;
while(n*(k-1)<m) n++;
n = (n-2)*k + m - (n-2)*(k-1)+1;
System.out.println(n);
}
}
else//否则
{
Main.factors(k);//找k的因子
long en = Main.howMany(m);//在m前已经有多少与k互斥的数
en = m-en;

for(long i=m+1;;i++)//从m+1开始逐一数与k互素的数
{
if(!Main.hasFactor(i)) en++;
if(en==m){System.out.println(i);break;}
}
}

}
}
}

#### Codeforces 920G-List Of Integers

2018-02-07 21:40:03

#### 算法笔记 - 数组

2017-05-02 22:02:26

#### HDU 6025 Coprime Sequence

2017-05-07 20:58:28

#### Codeforces 920G - List Of Integers 【容斥+二分】

2018-02-06 13:40:30

#### 写给在迷茫期的程序员（尤其是Java程序员）入行了一年，感觉不知道接下来该怎么做才能继续进步了，求指教

2014-07-13 23:26:45

#### C++ HOJ 猴子分桃

2015-07-09 18:58:10

#### 大家辛苦了

2006-06-27 10:44:00

#### 马云吃泡面咸菜照片引500万次围观 网友：辛苦了

2017-09-24 00:00:00

#### SDUT 1232-猴子分桃(逆推)

2014-10-23 20:53:53

#### 岁月不饶人，爸妈老了

2007-04-22 22:19:00