使用 C 语言中的 while 循环找出两个数字的最大公约数


问题

使用 C 编程语言找出任意两个数字的最大公约数。

解决方案

让用户从控制台输入任意两个数字。对于这两个数字,让我们找出最大公约数。

两个数字的最大公约数是能同时整除这两个数字且余数为零的最大数字。

我们用来找出两个数字最大公约数的逻辑如下 

while(b!=0) //check for b=0 condition because in a/b ,b should not equal to zero
   {
      rem=a % b;
      a=b;
      b=rem;
   }
Print a

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

程序 1

 现场演示

#include<stdio.h>
int main(){
   int a,b,rem;
   printf("enter any two numbers:");
   scanf("%d%d",&a,&b);
   while(b!=0) //check for b=0 condition because in a/b ,b should not equal to zero{
      rem=a % b;
      a=b;
      b=rem;
   }
   printf("GCD of two numbers is:%d
",a);    return 0; }

输出

enter any two numbers:8 12
GCD of two numbers is:4

Check: 8= 2 * 2 *2
      12= 2 * 2 * 3

The Greatest common divisor of two numbers is : 2 * 2 =4

程序 2

在这个示例中,让我们使用 for 循环找出两个数字的最大公约数 −

 现场演示

#include <stdio.h>
int main(){
   int num1, num2, i, GCD;
   printf("enter two numbers: ");
   scanf("%d %d", &num1, &num2);
   for(i=1; i <= num1 && i <= num2; ++i){
      if(num1%i==0 && num2%i==0)
         GCD = i;
   }
   printf("GCD of two numbers is:%d", GCD);
   return 0;
}

输出

enter two numbers: 24 48
GCD of two numbers is:24

更新于: 05-03-2021

6K+ 浏览量

开启您的 职业生涯

完成课程,获得认证

立即开始
广告