javascript 最大公約数を求める
- 作成日 2021.04.26
- 更新日 2022.08.18
- javascript
- javascript

javascriptで、最大公約数を求めるサンプルコードを記述してます。値が複数個ある場合でも、求めることは可能です。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 104.0.5112.81
最大公約数
以下のコードで、最大公約数を求めることが可能です。
function gcd (x, y){
if(x % y){
return gcd(y, x % y)
}else{
return y
}
}
console.log(gcd(15, 45))
// 15
アロー関数や三項演算子を使用すると、少し簡潔に記述できます。
const gcd = (x, y) => {
return (x % y) ? gcd(y, x % y) : y;
}
console.log( gcd(15, 45) )
// 15
値が複数個ある場合
値が複数個ある場合は、「arguments」を使うことで計算することが可能です
※アロー関数は「arguments」は使用できません。
const gcd = function () {
const f = (x, y) => y ? f(y, x % y) : x
let ans = arguments[0]
for (let i = 1; i < arguments.length; i++) {
ans = f(ans, arguments[i]);
}
return ans
}
console.log( gcd(15, 20, 30, 100) )
// 5
サンプルコード
以下は、
「実行」ボタンをクリックすると、ランダムな2桁の配列を2つ生成して最大公約数を求める
サンプルコードとなります。
※cssには「tailwind」を使用してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
</head>
<script>
function hoge() {
// ランダムな2桁の配列を生成
const arr = Array(2).fill().map(x => ~~(Math.random() * 100));
// 生成した配列を表示
disp(arr, "rand");
// 最大公約数を計算する関数
const f = (x, y) => y ? f(y, x % y) : x;
// 最大公約数
result.innerHTML = f(arr[0],arr[1]);
}
//フロントに表示する関数
function disp(arr, id) {
let text = [];
// 配列を利用してfor文を作成
[...arr].forEach((x, i) => text.push('<li class="list-group-item">' + arr[i] + '</li>'))
//innerHTMLを使用して表示
document.getElementById(id).innerHTML = text.join('');
}
window.onload = () => {
// クリックイベントを登録
btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
}
</script>
<body>
<div class="container mx-auto my-56 w-56 px-4">
<div class="flex justify-center">
<p id="result" class="bg-teal-500 text-white py-2 px-4 rounded-full mb-3 mt-4">最大公約数</p>
</div>
<div class="flex justify-center">
<ul id="rand"></ul>
</div>
<div class="flex justify-center">
<button id="btn" type="button"
class="mt-5 bg-transparent border border-red-500 hover:border-red-300 text-red-500 hover:text-red-300 font-bold py-2 px-4 rounded-full">
実行
</button>
</div>
</div>
</body>
</html>
最大公約数が計算されていることが確認できます。

-
前の記事
AlmaLinuxで最新版のgitを使用する 2021.04.25
-
次の記事
python openpyxlを使ってEXCELのセルの行列の数値指定からA1形式を取得する 2021.04.26
コメントを書く