C++ find the greatest common divisor and the least common multiple

Method 1: tossing and dividing

     Divide the "larger number" by the "smaller number", then divide the "smaller number" by the "first remainder", then divide the "first remainder" by the "second remainder",

     Repeat this until the last remainder is 0. If you are looking for the greatest common divisor of two numbers, then the final divisor is the greatest common divisor of the two numbers.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
intmain()
{
	int a,b;
	//while(scanf("%d,%d",&a,&b)!=EOF)//There is a problem with this writing, the value obtained by a*b is wrong, it seems to be the address value
	while((cin>>a>>b)!=NULL)
	{
		if(a<b)//Large numbers are placed in front
		{
			int temp=a;
			a=b;
			b=temp;
		}
		int gcd=0; //Greatest Common Divisor greatest common divisor;  
		int lcm=a*b; // Lowest Common Multiple;
		
		int t=0;
		while(b!=0)
		{
			t=a%b;
			a=b;
			b=t;
		}
		gcd=a;
		lcm=lcm/gcd;
		//cout<<gcd<<" "<<lcm<<endl;
		printf("%d %d\n",gcd,lcm);
	}
	return 0;
}

Method 2: More phase subtraction method

       Subtract "smaller number" from "larger number", loop, when two numbers are the same, the same number is the "greatest common divisor" #include <stdio.h>

 
 
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
int main(){int a,b;while((cin>>a>>b)!=NULL){int gcd=0; //Greatest Common Divisor 最大公约数; int lcm=a*b; // Lowest Common Multiple 最小公倍数; while(a!=b){if(a>b){a-=b;}else{b-=a;}}gcd=a;lcm=lcm/gcd;printf("%d %d\n",gcd,lcm);}return 0;}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325648580&siteId=291194637