Home >Backend Development >C#.Net Tutorial >How to find the greatest common divisor of two numbers in C language
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:
1. First, create a new C Language source program, the Visual C 6.0 software is used here.
#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);
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;
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; } }
5. Finally, click the icon above the toolbar, and then the source program is compiled and run to calculate the data.
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!