obsidian-notes/代码/最大公约数gcd.md

51 lines
804 B
Markdown
Raw Normal View History

2024-04-15 03:19:57 +00:00
---
title: 最大公约数gcd
updated: 2022-01-14 01:51:50Z
created: 2022-01-08 13:18:07Z
tags:
- mcu
- pll
- 代码块
---
# 含义
great common divisor, gcd
能够整除多个整数的最大正整数
# 算法
## 辗转相除法
$gcd(a,0)=a$
$gcd(a,b)=gcd(b,a mod b)$
如果参数都大于0那么可以简写成
$gcd(a,a)=a$
$gcd(a,b)=gcd(a-b,a), if \space a>b$
$gcd(a,b)=gcd(a,b-a), if \space a<b$
### 代码
```c
int gcd(int a, int b)
{
if(b)
{
while((a %= b) && (b %= a));
return a + b
}
}
```
```c
// greatest common denominator - euclid algo w/o recursion
uint32_t gcd_iter(uint32_t u, uint32_t v)
{
uint32_t t;
while (v) {
t = u;
u = v;
v = t % v;
}
return u ;
}
```
#mcu
#pll
#代码块