mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-02-27 20:02:15 -05: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--
Hailstone 数字序列可以从一个起始正整数 n 生成:
- If
nis1then the sequence ends - If
niseventhen the nextnof the sequence= n/2 - If
nisoddthen the nextnof the sequence= (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud), or as the Collatz sequence.
--instructions--
- Create a routine to generate the hailstone sequence for a number
- Your function should return an array with the number less than
limitwhich has the longest hailstone sequence and that sequence's length. (But don't show the actual sequence!)
--hints--
hailstoneSequence 应该是一个函数。
assert(typeof hailstoneSequence === 'function');
hailstoneSequence(30) should return an array.
assert(Array.isArray(hailstoneSequence(30)));
hailstoneSequence(30) should return [27, 112].
assert.deepEqual(hailstoneSequence(30), [27, 112]);
hailstoneSequence(50000) should return [35655, 324].
assert.deepEqual(hailstoneSequence(50000), [35655, 324]);
hailstoneSequence(100000) should return [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];
}