(C language) Given two numbers, find the greatest common divisor of the two numbers

Table of contents

method one

Method 2: Rolling and dividing


method one

Find the smaller value of the two numbers, and reduce it from the smaller value to the two numbers %, this number == 0.

//给定两个数,求这两个数的最大公约数
#include <stdio.h>

int main()
{
	int a = 0;
	int b = 0;
	
	scanf("%d %d", &a, &b);
	int c = (a < b ? a : b);
	while (c)
	{
		if (a % c == 0 && b % c == 0)
		{
			break;
		}
		c--;
	}
	printf("%d\n", c);
	return 0;
}

Method 2: Rolling and dividing

Example: Greatest Common Divisor of 18 and 24
First time: a = 18 b = 24 c = a%b = 18%24 = 18
      In the loop: a = 24 b=18
Second time: a = 24 b = 18 c = a%b = 24%18 = 6
      In the loop: a = 18 b = 6
The third time: a = 18 b = 6 c=a%b = 18%6 = 0
  end of loop
At this time, the content in b is the greatest common divisor of the two numbers.

#include <stdio.h>

int main()
{
	int a = 0;
	int b = 0;
	scanf("%d %d", &a, &b);
	int c = 0;
	while (c=a%b)
	{
		a = b;
		b = c;
	}
	printf("%d\n", b);
	return 0;
}

Of course, there are more ways, welcome to guide.

Guess you like

Origin blog.csdn.net/m0_63562631/article/details/131520189