[NYOJ] [1040] GCD and LCM

Problem Description

Loading...

Problem Analysis

Brushed up on the recursion for the greatest common divisor
(By the way, last time I used the repeated-subtraction method)
Hmm…
I really have kind of forgotten it…

cpp
1
2
3
4
5
6
int gcd(int a,int b) {
	if(b==0) {
		return a;
	}
	return gcd(b,a%b);
}

Problem AC code

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include<stdio.h>
int gcd(int a,int b) {
	if(b==0) {
		return a;
	}
	return gcd(b,a%b);
}
int main() {
	int T;
	scanf("%d",&T);
	while(T--) {
		int a,b;
		scanf("%d %d",&a,&b);
		printf("%d %d\n",gcd(a,b),a*b/gcd(a,b));
	}
	return 0;
}

The reference solution also uses Euclidean division
but it does not use a recursive function
It is written with a loop

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include<stdio.h>
int main() {
	unsigned int u,v,r,s,i,d;
	scanf("%u",&s);
	for(i=1; i<=s; i++) {
		scanf("%u%u",&u,&v);
		d=u*v;
		while(v!=0) {
			r=u%v;
			u=v;
			v=r;
		}
		printf("%u %u\n",u,d/u);
	}
	return 0;
}

Problem link: NYOJ 1040: Greatest Common Divisor and Least Common Multiple

Loading...