tft每日頭條

 > 圖文

 > c語言用函數寫兩個數的最大公約數

c語言用函數寫兩個數的最大公約數

圖文 更新时间:2024-07-23 05:17:23

題目要求:

編寫一個程序計算兩個正整數的最大公約數和最小公倍數。

題目分析:

所謂兩個數最大公約數就是指兩個數a,b的公共因數中最大的那一個。例如:4和8,兩個數的公共因數分别為1、2、4,其中4為4和8的最大公約數。

因此要計算出兩個數的最大公約數,最簡單的方法就是從兩個數中較小的那個開始依次遞減,得到的第一個這兩個數的公因子數即為這兩個數的最大公約數。

#include "stdio.h" int gcd(int a,int b){ /*最大公約數*/ int min; if(a<=0||b<=0) return -1; if(a>b) min = b; /*找到a、b中的較小的一個賦值給min*/ else min = a; while(min){ if(a%min == 0 && b%min == 0) /*判斷公因數*/ return min; /*找到最大公約數,返回*/ min--; /*沒有找到最大公約數,min減1*/ } return -1; } int lcm(int a,int b){ /*最小公倍數*/ int max; if(a<=0||b<=0) return -1; if(a>b) max = a; else max = b; /*找到a,b中的較大的一個賦值給max*/ while(max){ if(max%a == 0 && max%b == 0) /*判斷公倍數*/ return max; /*找到最小公倍數,返回*/ max ; /*沒有找到最小公倍數,max加1*/ } return -1; } main() { int a,b; printf("Please input two digit for getting GCD and LCM\n"); scanf("%d %d",&a,&b); printf("The GCD of %d and %d is %d\n",a,b,gcd(a,b)); /*打印出a、b的最大公約數*/ printf("The LCM of %d and %d is %d\n",a,b,lcm(a,b)); /*打印出a、b的最小公倍數*/ getche(); }

c語言用函數寫兩個數的最大公約數(c語言求兩個數的最大公約數和最小公倍數)1

10和15的最大公約數和最小公倍數

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关圖文资讯推荐

热门圖文资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved