当前位置:网站首页>辗转相除法
辗转相除法
2022-07-27 05:01:00 【叶辰 .】
辗转相除法
话不多说,先上最强代码:
int gcd(int a, int b){
return b == 0 ? a : gcd(b, a % b);
}
此函数返回值就为a和b的最大公约数
辗转相除法的介绍
辗转相除 可以求最大公约数,顾名思义,反复的除,最终得到两数的最大公约数。
首先我们来分析下定理:
定理:两个整数的最大公约数等于其中较小的那个数和两数相除余数的最大公约数。最大公约数(Greatest Common Divisor)缩写为GCD。
gcd(a,b) = gcd(b,a mod b) (不妨设a>b 且r=a mod b ,r不为0)
文字不好理解,举个实例:
134 / 18 = 7 … 8
18 / 8 = 2 … 2
8 / 2 = 4 … 0
看清了吧,是不是和定理一模一样,所以我们要找最大公约数,而134 /18的和8 / 2的最大公约数相等,所以我们只需要求出8 / 2的最大公约数,是不是就是开头说的换了两个数再求,而我们要知道,因为两数相除,余数为0,其除数必定为最大公约数,所以这里的2也就是我们要找的138 / 18 的最大公约数。至于证明,百度搜索,都有。主要证明思路就是,有a/b余r一式, 先假设y为a,b的公约数,再证明b,r的公约数也为y。
再上个流程图:
代码实现:
int gcd(int a,int b){
int r=1;// 余数,赋初值为1
while(r!=0){
// 如果a<b,亦无需颠倒ab,在计算中商0余除数本身,在下次运算中自可颠倒回来
r = a % b;
a = b;
b = r;
}
return a;
}
边栏推荐
- OFDM 16 lecture 2-ofdm and the DFT
- Detailed description of binary search tree
- What if Photoshop prompts that the temporary storage disk is full? How to solve the problem that PS temporary storage disk is full?
- Hiding skills of Photoshop clipping tool
- 《Robust and Precise Vehicle Localization based on Multi-sensor Fusionin Diverse City Scenes》翻译
- JVM Part 1: memory and garbage collection part 14 -- garbage collector
- JVM上篇:内存与垃圾回收篇十--运行时数据区-直接内存
- Another skill is to earn 30000 yuan a month+
- 知识点总结(一)
- "Photoshop2021 tutorial" align and distribute to make dot patterns
猜你喜欢

Detailed explanation of mvcc and its principle

pyside2____1.安装和案列

Li Kou achieved the second largest result

【牛客讨论区】第七章:构建安全高效的企业服务

Use of collection framework

Knapsack problem DP

Another skill is to earn 30000 yuan a month+

JVM上篇:内存与垃圾回收篇九--运行时数据区-对象的实例化,内存布局与访问定位

TypeScript 详解

When using Photoshop, the prompt "script error -50 general Photoshop error appears“
随机推荐
Sub database and sub table
MySQL download and installation & perfect uninstall
Constraints of MySQL table
Why is count (*) slow
Acticiti中startProcessInstanceByKey方法在variable表中的如何存储
OFDM 十六讲 2- OFDM and the DFT
再一个技巧,每月稳赚3万+
精选用户故事|洞态在聚水潭的误报率几乎为0,如何做到?
【牛客讨论区】第七章:构建安全高效的企业服务
Jmeter 界面如何汉化?
[untitled] I is circularly accumulated under certain conditions. The condition is usually the length of the loop array. When it exceeds the length, the loop will stop. Because the object cannot judge
Standard dialog qmessagebox
How idea creates a groovy project (explain in detail with pictures and texts)
听过最自律的一句话: 那些我难以言表 不作声响
2、 MySQL advanced
How does PS import LUT presets? Photoshop import LUT color preset tutorial
树莓派输出PWM波驱动舵机
kali系统arp介绍(断网嗅探密码抓包)
How to sinicize the JMeter interface?
Three paradigms, constraints, some keyword differences,