It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
The following code works on SpiderMonkey 1.8.5. But didn't work on my nodejs.
It takes about two seconds, and gives the correct answer.
My two major concerns are my style. And my choice in functions.
Personally I think str_sorted
is horrible, int
-> str
-> array
-> str
.
// Like Python's range.
function range(start, stop, step){
if (typeof(stop)==='undefined'){
stop = start;
start = 0;
}
if (typeof(step)==='undefined') step = 1;
if (stop === null){
while (true){
yield start;
start += step;
}
}else{
for (number = start; number < stop; number += step){
yield number;
}
}
}
function str_sorted(num){
num = num.toString();
arr = Array();
for (index in num){
arr.push(num[index]);
}
return arr.sort().join('');
}
function permuted(num){
tmp = str_sorted(num);
return tmp == str_sorted(num * 2) &&
tmp == str_sorted(num * 3) &&
tmp == str_sorted(num * 4) &&
tmp == str_sorted(num * 5) &&
tmp == str_sorted(num * 6);
}
function find(iterable, fn){
for (num in iterable){
if (fn(num)){
return num;
}
}
}
print(find(range(1, null), permuted));
The way that I run this code is via the command line.
$ js p52.js
142857
$
This runs the the SpiderMonkey 1.8.5 interpreter. I got it from the Arch repository at some point.
yield
? In a normal function? Did you meanfunction* range(...
? \$\endgroup\$print
came from? \$\endgroup\$yield
is an ECMAScript 2015 (previously known as ECMAScript 6 or ES6 for short) feature. It only works together with generators (function*
). Which is why I find it surprising that this code even works to begin with :o \$\endgroup\$yield
keyword should be a syntax error because it's a reserved word. \$\endgroup\$