3 ms·
Not that it will help with this exact situation, but there's actually a trick to find out divisibility of 3 [1]. Basically it states: the sum of the digits of a
by johnsonjo 7y ago
Not that it will help with this exact situation, but there's actually a trick to find out divisibility of 3 [1]. Basically it states: the sum of the digits of a number, N, are divisible by 3 if an only if the number N itself is divisible by 3.
[1]: https://en.wikipedia.org/wiki/Divisibility_rule#Divisibility_by_3_or_9 https://en.wikipedia.org/wiki/Divisibility_rule#Divisibility...
- raverbashing 7y agoIt is exactly the way I'm thinking. More importantly, the order of the digits doesn't matter, so if 12 is divisible, so is 21, 102, etc. Though maybe the two approaches can be combined
- johnsonjo 7y agoSure maybe something like this. It's not very performant, but it uses some math skills: console.clear(); /** naive python like range in JS */ function* range (beg, end) { for(let i = beg; i < end; ++i) { // stringify the number yield '' + i; } } function buzz (stringNum) { const lastChar = stringNum.charAt(stringNum.length - 1); return lastChar === '5' || lastChar === '0'; } const mapping = [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1]; function fizz (stringNum) { return ( stringNum // get each character of the string .split('') // find out if total digits are divisible by three. .reduce((acc, x) => (acc + mapping[x]) % 3, 0) === 0 ); } function fizzBuzz (stringNum) { const f = fizz(stringNum), b = buzz(stringNum); if(f && b) { return 'FizzBuzz'; } else if (f) { return 'Fizz'; } else if (b) { return 'Buzz'; } else { return stringNum; } } const nums = [...range(1,1001)]; const result = nums // main algo .map(fizzBuzz) console.log(result.join('\n')); EDIT: sorry I didn't see your other reply below another comment. I now see this does not fulfill the requirements.