๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ์ธ๊ณต๋ถ€/Algorithm

[๋ฐฑ์ค€][Node.js] 6064๋ฒˆ : ์นด์ž‰ ๋‹ฌ๋ ฅ

by ๐Ÿ‡๋ฐ•๋ด‰๋ด‰๐Ÿ‡ 2021. 12. 2.

 

 

Algorithm

-  ์นด์ž‰ ๋‹ฌ๋ ฅ -

 


 

๋ฌธ์ œ

์ตœ๊ทผ์— ICPC ํƒ์‚ฌ๋Œ€๋Š” ๋‚จ์•„๋ฉ”๋ฆฌ์นด์˜ ์ž‰์นด ์ œ๊ตญ์ด ๋†€๋ผ์šด ๋ฌธ๋ช…์„ ์ง€๋‹Œ ์นด์ž‰ ์ œ๊ตญ์„ ํ† ๋Œ€๋กœ ํ•˜์—ฌ ์„ธ์›Œ์กŒ๋‹ค๋Š” ์‚ฌ์‹ค์„ ๋ฐœ๊ฒฌํ–ˆ๋‹ค. ์นด์ž‰ ์ œ๊ตญ์˜ ๋ฐฑ์„ฑ๋“ค์€ ํŠน์ดํ•œ ๋‹ฌ๋ ฅ์„ ์‚ฌ์šฉํ•œ ๊ฒƒ์œผ๋กœ ์•Œ๋ ค์ ธ ์žˆ๋‹ค. ๊ทธ๋“ค์€ M๊ณผ N๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ๋‘ ๊ฐœ์˜ ์ž์—ฐ์ˆ˜ x, y๋ฅผ ๊ฐ€์ง€๊ณ  ๊ฐ ๋…„๋„๋ฅผ <x:y>์™€ ๊ฐ™์€ ํ˜•์‹์œผ๋กœ ํ‘œํ˜„ํ•˜์˜€๋‹ค. ๊ทธ๋“ค์€ ์ด ์„ธ์ƒ์˜ ์‹œ์ดˆ์— ํ•ด๋‹นํ•˜๋Š” ์ฒซ ๋ฒˆ์งธ ํ•ด๋ฅผ <1:1>๋กœ ํ‘œํ˜„ํ•˜๊ณ , ๋‘ ๋ฒˆ์งธ ํ•ด๋ฅผ <2:2>๋กœ ํ‘œํ˜„ํ•˜์˜€๋‹ค. <x:y>์˜ ๋‹ค์Œ ํ•ด๋ฅผ ํ‘œํ˜„ํ•œ ๊ฒƒ์„ <x':y'>์ด๋ผ๊ณ  ํ•˜์ž. ๋งŒ์ผ x < M ์ด๋ฉด x' = x + 1์ด๊ณ , ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด x' = 1์ด๋‹ค. ๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ ๋งŒ์ผ y < N์ด๋ฉด y' = y + 1์ด๊ณ , ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด y' = 1์ด๋‹ค. <M:N>์€ ๊ทธ๋“ค ๋‹ฌ๋ ฅ์˜ ๋งˆ์ง€๋ง‰ ํ•ด๋กœ์„œ, ์ด ํ•ด์— ์„ธ์ƒ์˜ ์ข…๋ง์ด ๋„๋ž˜ํ•œ๋‹ค๋Š” ์˜ˆ์–ธ์ด ์ „ํ•ด ์˜จ๋‹ค.

 

์˜ˆ๋ฅผ ๋“ค์–ด, M = 10 ์ด๊ณ  N = 12๋ผ๊ณ  ํ•˜์ž. ์ฒซ ๋ฒˆ์งธ ํ•ด๋Š” <1:1>๋กœ ํ‘œํ˜„๋˜๊ณ , 11๋ฒˆ์งธ ํ•ด๋Š” <1:11>๋กœ ํ‘œํ˜„๋œ๋‹ค. <3:1>์€ 13๋ฒˆ์งธ ํ•ด๋ฅผ ๋‚˜ํƒ€๋‚ด๊ณ , <10:12>๋Š” ๋งˆ์ง€๋ง‰์ธ 60๋ฒˆ์งธ ํ•ด๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค. 

 

๋„ค ๊ฐœ์˜ ์ •์ˆ˜ M, N, x์™€ y๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ, <M:N>์ด ์นด์ž‰ ๋‹ฌ๋ ฅ์˜ ๋งˆ์ง€๋ง‰ ํ•ด๋ผ๊ณ  ํ•˜๋ฉด <x:y>๋Š” ๋ช‡ ๋ฒˆ์งธ ํ•ด๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š”์ง€ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜๋ผ. 

 

์ž…์ถœ๋ ฅ ์˜ˆ์‹œ

 

๋ฌธ์ œ ํ’€๊ธฐ

const readline = require("readline");
const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout,
});
let input = [];
rl.on("line", function (line) {
	input.push(line.toString());
}).on("close", function () {
	for (let i = 1; i <= +input[0]; i++) {
		let arr = input[i].split(" ");
		let M = +arr[0],
			N = +arr[1],
			x = +arr[2],
			y = +arr[3];
		let lcm = (M * N) / gcd(M, N);
		let n = 0;
		let value = -1;
		while (n * M < lcm) {
			if ((n * M + x - y) % N === 0) {
				value = n * M + x;
				break;
			}
			n++;
		}
		console.log(value);
	}
	process.exit();
});

let gcd = (n1, n2) => {
	return n2 ? gcd(n2, n1 % n2) : n1;
};

 

 

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€