euclid辗转相除法求greatest common divisor

原创
2013/01/28 00:36
阅读数 151

实现过程。

用大数a除小数b,直到余数为0,如果余数不为0{

则将小数赋给大数,

余数赋给小数

}

我的代码:

int main(void) {
	int a, b,yushu;
	printf("input integer a:");
	scanf("%i",&a);
	printf("input integer b:");
	scanf("%i",&b);

	while((yushu = a % b) !=0){
		a = b;
		b = yushu;
	}
	printf("gcd is %i",b);

	return 0;
}

参考答案《programming in c 3rd edition》:

int main(void) {
	int u, v, temp;
	printf("Please type in two nonnegative integers.\n");
	scanf("%i%i", &u, &v);
	while (v != 0) {
		temp = u % v;
		u = v;
		v = temp;
	}
	printf("Their greatest common divisor is %i\n", u);
	return 0;
}

go实现

package main

import "fmt"

func main() {
	fmt.Printf("Please type in two nonnegative integers.\n")
	var u, v, temp int
	fmt.Scanf("%d%d", &u, &v)
	for v != 0 {
		temp = u % v
		u = v
		v = temp
	}
	fmt.Printf("Their greatest common divisor is %v", u)
}

展开阅读全文
加载中
点击加入讨论🔥(3) 发布并加入讨论🔥
打赏
3 评论
2 收藏
0
分享
返回顶部
顶部