mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-09 14:18:42 +08:00
* Retranslate the complete Japanese online edition from Chinese * Fit Japanese homepage labels and localize heading permalinks * Point Japanese contribution instructions to the Japanese preview * Replace locale conditionals with multilingual UI tables
71 lines
1.6 KiB
JavaScript
71 lines
1.6 KiB
JavaScript
/**
|
||
* File: iteration.js
|
||
* Created Time: 2023-08-28
|
||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||
*/
|
||
|
||
/* for ループ */
|
||
function forLoop(n) {
|
||
let res = 0;
|
||
// ループで 1, 2, ..., n-1, n の和を求める
|
||
for (let i = 1; i <= n; i++) {
|
||
res += i;
|
||
}
|
||
return res;
|
||
}
|
||
|
||
/* while ループ */
|
||
function whileLoop(n) {
|
||
let res = 0;
|
||
let i = 1; // 条件変数を初期化する
|
||
// ループで 1, 2, ..., n-1, n の和を求める
|
||
while (i <= n) {
|
||
res += i;
|
||
i++; // 条件変数を更新する
|
||
}
|
||
return res;
|
||
}
|
||
|
||
/* while ループ(2 回の更新) */
|
||
function whileLoopII(n) {
|
||
let res = 0;
|
||
let i = 1; // 条件変数を初期化する
|
||
// ループで 1, 4, 10, ... の和を求める
|
||
while (i <= n) {
|
||
res += i;
|
||
// 条件変数を更新する
|
||
i++;
|
||
i *= 2;
|
||
}
|
||
return res;
|
||
}
|
||
|
||
/* 二重 for ループ */
|
||
function nestedForLoop(n) {
|
||
let res = '';
|
||
// i = 1, 2, ..., n-1, n のループ
|
||
for (let i = 1; i <= n; i++) {
|
||
// j = 1, 2, ..., n-1, n のループ
|
||
for (let j = 1; j <= n; j++) {
|
||
res += `(${i}, ${j}), `;
|
||
}
|
||
}
|
||
return res;
|
||
}
|
||
|
||
/* 実行用コード */
|
||
const n = 5;
|
||
let res;
|
||
|
||
res = forLoop(n);
|
||
console.log(`for ループで求めた和 res = ${res}`);
|
||
|
||
res = whileLoop(n);
|
||
console.log(`while ループで求めた和 res = ${res}`);
|
||
|
||
res = whileLoopII(n);
|
||
console.log(`while ループ(2 回の更新)で求めた和 res = ${res}`);
|
||
|
||
const resStr = nestedForLoop(n);
|
||
console.log(`二重 for ループの走査結果 ${resStr}`);
|