mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-04-12 01:00:13 -04:00
2.0 KiB
2.0 KiB
id, title, challengeType, forumTopicId, dashedName
| id | title | challengeType | forumTopicId | dashedName |
|---|---|---|---|---|
| 595608ff8bcd7a50bd490181 | Hailstone sequence | 1 | 302279 | hailstone-sequence |
--description--
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
- If
nis1then the sequence ends - 如果
n是even,则序列的下一个n= n/2 - 如果
n是odd,则序列的下一个n= (3 * n) + 1
(未经证实的)科拉茨猜想是任何起始数字的冰雹序列总是终止。
冰雹序列也称为冰雹数(因为这些值通常像云中的冰雹一样受到多次下降和上升的影响),或称为 Collatz 序列。
--instructions--
- Create a routine to generate the hailstone sequence for a number
- 你的函数应该返回一个小于
limit的数组,它具有最长的冰雹序列和该序列的长度。 (但不要显示实际序列!)
--hints--
hailstoneSequence 应该是一个函数。
assert(typeof hailstoneSequence === 'function');
hailstoneSequence(30) 应该返回一个数组。
assert(Array.isArray(hailstoneSequence(30)));
hailstoneSequence(30) 应该返回 [27, 112]。
assert.deepEqual(hailstoneSequence(30), [27, 112]);
hailstoneSequence(50000) 应该返回 [35655, 324]。
assert.deepEqual(hailstoneSequence(50000), [35655, 324]);
hailstoneSequence(100000) 应该返回 [77031, 351]。
assert.deepEqual(hailstoneSequence(100000), [77031, 351]);
--seed--
--seed-contents--
function hailstoneSequence(limit) {
const res = [];
return res;
}
--solutions--
function hailstoneSequence (limit) {
function hailstone(n) {
const seq = [n];
while (n > 1) {
n = n % 2 ? 3 * n + 1 : n / 2;
seq.push(n);
}
return seq;
}
let n = 0;
let max = 0;
for (let i = limit; --i;) {
const seq = hailstone(i);
const sLen = seq.length;
if (sLen > max) {
n = i;
max = sLen;
}
}
return [n, max];
}