obsidian-notes/代码/最大公约数gcd.md
CSSC-WORK\murmur 3e6078442b init version
2024-04-15 11:19:57 +08:00

51 lines
804 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
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
#代码块