Home  >  Article  >  Backend Development  >  How to find the greatest common divisor of two numbers in C language

How to find the greatest common divisor of two numbers in C language

coldplay.xixi
coldplay.xixiOriginal
2020-08-19 16:02:2228563browse

C language method to find the greatest common divisor of two numbers: First create a new C language source program, and directly input two positive integers a and b; then take the larger of the two numbers a and b. The small value is stored in the variable n; then starting from the smaller of the two numbers a and b, decrease by 1 one by one; and finally click the run icon above the toolbar.

How to find the greatest common divisor of two numbers in C language

How to find the greatest common divisor of two numbers in C language:

1. First, create a new C Language source program, the Visual C 6.0 software is used here.

How to find the greatest common divisor of two numbers in C language

#2. Then enter two positive integers a and b directly from the keyboard.

The code is:

printf("please input two number:\n");
int a,b;
scanf("%d%d",&a,&b);

How to find the greatest common divisor of two numbers in C language

3. Then take the smaller value of the two numbers a and b and store it in the variable n.

The code is:

int n=a;
if (n>b)
n=b;

How to find the greatest common divisor of two numbers in C language

4. Then start from the smaller of the two numbers a and b, and decrease it by 1 one by one, so that you can Find the integers that divide a and b. The first integer found is the greatest common divisor of integers a and b.

Code:

for(int i=n;i>=1;i--)
{
if (a%i==0&&b%i==0)
{
printf("最大公约数:%d \n",i);
break;
}
}

How to find the greatest common divisor of two numbers in C language

5. Finally, click the icon above the toolbar, and then the source program is compiled and run to calculate the data.

How to find the greatest common divisor of two numbers in C language

Related learning recommendations: C video tutorial

The above is the detailed content of How to find the greatest common divisor of two numbers in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn