Skip to content

Instantly share code, notes, and snippets.

@daftAnorak
Last active February 8, 2023 17:26
Show Gist options
  • Save daftAnorak/527616c2d1cbce3e84e3ef6fe63695c9 to your computer and use it in GitHub Desktop.
Save daftAnorak/527616c2d1cbce3e84e3ef6fe63695c9 to your computer and use it in GitHub Desktop.
Code Exercise for JS Position - Magic Numbers
/**
* Method which takes a given, natural number and calculates
* a series of magic numbers until a number repeats (returns false),
* or equals 1 (returns true).
*
* EX: fn(1) === true // (1 equals 1)
* EX: fn(7) === true // (7 -> 49 -> 97 -> 130 -> 10 -> 1)
* EX: fn(11) === false // (11 -> 2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 [repeat])
*
* @param {number} x - given, natural number
* @returns {boolean} whether the magic numbers repeat (false) OR return 1 (true)
*/
function magicNumbers(x) {
const prevMagicNumbers = new Set();
while (x !== 1) {
prevMagicNumbers.add(x);
x = String(x).split('').reduce((a, b) => a + b * b, 0);
if (prevMagicNumbers.has(x)) return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment