GDUT2022级专题四数论课后练习K - Happy 2006

该程序旨在找出给定整数m的相对素数序列中,按升序排列的第K个数。首先,通过循环计算所有小于m的数与m的GCD,将相对素数存储到数组中。然后,根据K值确定目标位置并输出结果。代码使用了C++编写,通过直接计算和数组索引来找到答案。
摘要由CSDN通过智能技术生成

题目描述:

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.大意:

如果大公约数(GCD)为1,则两个正整数被称为相对素数。例如,1、3、5、7、9……都是2006年的相对素数。

现在你的工作很简单:对于给定的整数m,找到第K个元素,当这些元素按升序排序时,它对m是相对素数

输入格式

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

输入包含多个测试用例。对于每个测试用例,它包含两个整数m(1<=m<=1000000)、K(1<=K<=100000000)。

输出格式:

Output the K-th element in a single line.

在单行中输出第K个元素。

输入输出样例

输入 #1

2006 1

2006 2

2006 3

输出 #1

1

3

5

思路:

先打表把m的相对素数(小于m)都找到,根据数据范围,可以直接for循环,不用筛,再找到在第几个m的第几个相对素数。

代码:

#include <iostream>
#include <cstdio>
using namespace std;
#pragma GCC optimize(2)


int a,b;
const int n=1e6;
int p[n+5]={};
int gcd(int a,int b){
	if(b==0){
		return a;	
	}
	return gcd(b,a%b);
}

int main(){
	while(cin>>a>>b){
		int sum=0;
		for(int i=1;i<=a;++i){
			if(gcd(i,a)==1){
				p[++sum]=i;
			}
		}
		int c,d;
		c=b%sum;
		d=b/sum;
		if(c==0){
			d--;
			c=sum;
		}
		printf("%d\n",p[c]+d*a);
	}

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值