C language example-find the greatest common divisor of two numbers

The user enters two numbers and finds the greatest common divisor of the two numbers.

  1. Toss and turns to divide
    with a larger number to find the remainder of the smaller number, if the remainder is 0, the divisor is the greatest common divisor. If the remainder is not 0, use this remainder as the divisor, and the original smaller number as the dividend, and recalculate the remainder until the remainder is 0.
    Toss and divide
    Code
#include <stdio.h>
int main()
{
    
    
int x,y,z;
scanf("%d %d",&x,&y);
while(x%y!=0)
{
    
    
	z=x%y;
	x=y;
	y=z;
}
printf("最大公约数%d",y);
return 0;
}
  1. Subtraction When
    two numbers are equal, the greatest common divisor is any one of them. When they are not equal, use the larger number to subtract the smaller number. Comparison of the number of smaller difference obtained before and, if not, etc., repeat the previous step, until the two numbers are equal
    Subtraction
    Code
#include <stdio.h>
int main()
{
    
    
int x,y;
scanf("%d %d",&x,&y);
while(x!=y)
{
    
    
	if(x>y)
	x=x-y;
	else {
    
    
	y=y-x;
	}
}
printf("最大公约数%d",y);
return 0;
}
  1. Exhaustive method
    If the larger number can divide the smaller number evenly, then the greatest common divisor is the smaller number. If the smaller number cannot be divided evenly, then the two numbers are divided by the smaller number in order from the largest to the smallest. The divisor that can be divided evenly is the greatest common divisor.
    Enumeration
    Code
#include <stdio.h>
int main()
{
    
    
int x,y,z;
scanf("%d %d",&x,&y);
if(x>y)
z=y;
else
z=x;
while(1)
{
    
    
	if(x%z==0&&y%z==0)
	break;
	else 
	z--;
}
printf("最大公约数%d",z);
return 0;
}
  • Problems arise
    scanf function and% d% d% d,% d, the difference between the former two variables can be separated by a space Enter the tab key, which can only be separated by commas

Guess you like

Origin blog.csdn.net/qq_41017444/article/details/112427196