判断2个正整数是否互质
1. Two positive integers i and j are considered to be co-prime if there exists no integer greater than 1 that divides them both.
Write a function co-prime that has two input parameters, i and j, and returns a value of 1 for true if i and j are co-prime.
Otherwise, co-prime should return a value of 0 for false. Also, write a driver program to test the your function.
You should specify the input / output format of your program.
使用欧几里得算法(辗转相除法)
GCD is stand for greatest common divisor最大公约数
Hint - You can use the Euclidean Algorithm which is outlined as below:
To find the greatest common divisor between two natural numbers, divide one by the other and take the remainder (i.e. modulus operation).
为了找到2个自然数a,b的最大公约数,用一个数a除以另外一个数b,取余数
If the remainder is non-zero, take the divider and the modulus as the input and repeat the modulus operation until the modulus becomes zero.
如果余数不是0,把除数和余数作为输入,重复求余的操作。直到余数变为0
The last divider used before the modulus becomes zero is the greatest common divisor (GCD) between the two numbers that we start out with.
在余数变为0前的最后一个除数,是2个数字的最大公约数
If the GCD is 1, then the two numbers are co-prime (i.e. relatively prime). (30 points)
如果最大公约数是1,那么这2个数字互质
Example 1: Find the GCD of 84 and 140.
140 % 84 = 56 , 84 % 56 = 28, 56 % 28 = 0
\ the GCD of 84 and 140 is 28 Þ not co-prime.
Example 2: Find the GCD of 12 and 35
12 % 35 = 12, 35 % 12 = 11, 12 % 11 = 1, 11 % 1 = 0
\ the GCD of 35 and 12 is 1 Þ co-prime.
public static bool CoPrime(int a,int b) { bool flag = false; int c; while (true) { c = a % b; if (c == 0) { if (b == 1) { flag = true; } break; } a = b; b = c; } return flag; }
作者:Chuck Lu GitHub |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(三):用.NET IoT库
· 【非技术】说说2024年我都干了些啥
2014-07-07 ubuntu12 root账户自动登录
2014-07-07 ZedGraph如何动态的加载曲线