求最大公约数伪代码
对于求两个数的最大公约数,有欧几里得算法,即辗转相除法。
算法解释
对于两个正整数a,b,若求最大公约数,大体算法步骤如下:
- 用其中一个数a作除数,用另一个数b作被除数,求出作除法后的余数值,记为remainder。
- 判断remainder是否为0。若为0,则b为最大公约数并退出步骤,否则执行下一步。
- 将a的值改为b的值,之后将b的值改为remainder的值。
- 回到步骤1.
这里也提供一个更为详细的解释:欧几里得算法_百度百科 (baidu.com)
伪代码
Write "Please input two numbers" Read a, b Set remainder to a REM b While(c is not zero) Set a to b Set b to remainder Set remainder to a REM b Write "The greatest common divisor is ", remainder
伪代码测试
| team 1 | a | b | remainder |
| input | 56 | 24 | |
| first | 56 | 24 | 8 |
| second | 24 | 8 | 0 |
| output | 8 |
| team 2 | a | b | remainder |
| input | 38 | 247 | |
| first | 38 | 247 | 38 |
| second | 247 | 38 | 19 |
| third | 38 | 19 | 0 |
| output | 19 |
| team 3 | a | b | remainder |
| input | 97 | 17 | |
| first | 97 | 17 | 12 |
| second | 17 | 12 | 5 |
| third | 12 | 5 | 2 |
| fourth | 5 | 2 | 1 |
| fifth | 2 | 1 | 0 |
| output | 1 |
这些组别经验证后,得知是结果正确的,故该算法有一定的适用性。
浙公网安备 33010602011771号