持续更新蓝桥杯算法训练题解,有兴趣可以关注一波呀。
题目
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
5
题解
题目和Poj 2773是完全一样的,但是代码一样会超时。最坑的是他给的输入,格式和他描述的根本不一样。所以这个题直接取Poj做就完了,没必要从这浪费时间了。
题目是根据一个性质计算的,如果a和b互素那么b * t + a也和b互素。
所以可以先算出小于n和并且与n互素的数字,假设个数为j,放在了数组a中。然后对于大于n的数字可以使用上述性质进行计算。大于k的第一个数字为
n * 1 + a[0], 大于k的第二个数字为n * 1 + a[1]… 大于k的第k个数字为 ( k − 1 ) / j + a ( ( k − 1 ) (k - 1) / j + a((k - 1) % j) (k−1)/j+a((k−1)
也就是说每j个数字是一个循环。
a[0], a[1], a[2]… a[j - 1]
n + a[0], n + a[1], … n + a[j - 1]
2n + a[0], 2n + a[1] … 2n + a[j - 1]
…
第k个,也就是对应的id为k - 1。那么对应的行列的值为 ( k − 1 ) / j + a ( ( k − 1 ) (k - 1) / j + a((k - 1) % j) (k−1)/j+a((k−1)
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6+ 5;
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; // 在[1, n]中有j个数字和n互素,如果
k--;
printf("%d\n", k / j * n + a[k % j]);
}
return 0;
}
时间复杂度 O ( n l o g n ∗ c a s e ) O(nlogn * case) O(nlogn∗case)
- 如果看时间复杂度,确实有可能会超时,因为 1 e 6 ∗ 1 e 3 = 1 e 9 1e6 * 1e3 = 1e9 1e6∗1e3=1e9的时间复杂度。但是时间复杂度
- 可以优化一下求约数的代码,但是不知道怎么优化,暂时不想了。