Is this prime?
isthisprime.com
isthisprime.com
setInterval(function() {
var n = parseInt(document.querySelector("#n").textContent);
document.querySelector(is_prime(n) === "prime" ? "#yes" : "#no").click();
}, 0);
document.querySelector("#start").click();
EDIT: replaced my isPrime with the one already in the game.EDIT 2: There appears to be some sort of increasing delay (pretty sure it's not just `is_prime` being slow) starting around 500 points. Maybe the game itself trying to compute primes?
var yes = document.getElementById('yes'),
no = document.getElementById('no'),
n = document.getElementById('n'),
start = document.getElementById('start');
function tick() {
console.log('tick');
if (is_prime(n.innerHTML) === 'prime') {
yes.click();
} else {
no.click();
}
window.setTimeout(tick, 500);
}
start.click();
tick(); game.check = function (answer) {
this.streak += 1;
this.next_n();
}
setInterval(function() {
document.querySelector("#yes").click();
}, 0);
document.querySelector("#start").click();
(High score of 15,000!) function isPrime(n){
if ((n<=1) || (!n % 2)) {
return false;
}
for (var k = 3; k < Math.round(Math.sqrt(n) + 0.5); k = k+2) {
if (n % k == 0) {
return false;
}
}
return true;
}
var nSpan = $("span#n")
var yesButton = $("button#yes");
var noButton = $("button#no");
var body = $("body");
function solve(){
if (isPrime(parseInt(nSpan.innerHTML)) {
yesButton.click();
} else {
noButton.click();
}
if (body.className != "end") {
setTimeout(solve,0);
}
}
solve(); game.check = function() {
this.streak = Number.MAX_VALUE;
this.next_n();
};
document.querySelector("#start").click();
document.querySelector("#yes").click();Beyond that it'd be nice to build a list of previously determined primes to reduce your number of checks, but I guess at that point it might just be better to implement classic primality tests...
Conversions are still somewhat expensive, but I do know compared to polynomial time or a large enough constant, it can be a better choice for an optimization. For example, computing log10 of an integer.
(n+1)^2 = n^2 + 2n + 1
That gets you: def squares:
n = 1
nSquared = 1
delta = 1
while nSquared <= n:
n += 1
yield n
delta += 2
nSquared += delta
but as others said, once your limit is large enough, the relatively large cost of computing a square root once may be lower than the O(sqrt(n)) additions in this loop.(Quick check: if you use a binary search to find sqrt(n), you need 2log(n) iterations, each of which requires a division by two (for integers, that is a bit shift) and one addition. A linear search takes sqrt(n) iterations, each with three additions. For whatever ratio of speed of operations you pick, the former will be faster for sufficiently large n)
When asked about modern day performance, I would just say “I do not know”. Thing is that those muls, on modern CPUs, might be pipelined in parallel with the adds, so that, time wise, you would get them for free.
But of course, it might be possible to get that sqrt for free, too. Even if it takes 50 cycles, you might start one, do a few iterations without checking for ‘reached sqrt(n) yet’, and then start a loop testing for the limit.
If you really want to know for x_64, http://www.agner.org/optimize/ probably has the answers, but then, you would have to know the x86 instruction set, which is horrendous (compared to that 6502 or 68000). Even realising that there will be single, double and vector variants, the number of different instructions with ‘SQRT’ in their name I find in http://www.agner.org/optimize/instruction_tables.pdf is insane.
And of course, probably, something completely out of left field could well be the fastest way to do this (by a few ns, probably). For example, modern CPUs can count leading zeros in an integer. If that instruction is fast (for x86, that is not a given; ‘bit scan reverse’ was slow on some CPUs) subtract from 64/32/16, and halve, and you have a decent approximation to 2log(sqrt(n)) (using ‘if n has b bits, sqrt(n) has about b/2’)
The effect is more significant with larger numbers:
arc> (newton-steps (round (* 3/2 (expt 2 1000))) 1)
508
arc> (newton-steps (round (* 3/2 (expt 2 1000))) (expt 2 500))
8> But of course, it might be possible to get that sqrt for free, too. Even if it takes 50 cycles, you might start one, do a few iterations without checking for ‘reached sqrt(n) yet’, and then start a loop testing for the limit.
On the CPU side, the branch predictor might make the sqrt free by pipelining it, but that starts to make the analysis a bit harder. Strange things can happen when you introduce branch prediction. The performance would also depend on ALU/FPU contention, hyperthreads, etc...
> If you really want to know for x_64, http://www.agner.org/optimize/ probably has the answers, but then, you would have to know the x86 instruction set, which is horrendous (compared to that 6502 or 68000). Even realising that there will be single, double and vector variants, the number of different instructions with ‘SQRT’ in their name I find in http://www.agner.org/optimize/instruction_tables.pdf is insane.
I've only just started reading Agner Fog's documentation (which is awesome), but it definitely seems like the place the find low level information of the ilk when it's needed. If you read through the instruction table though, you probably noticed there are fsqrt and (v)sqrt(p)(s/d). For most purposes, x87 is actually deprecated and SSE2, the latter, is preferred for scalar floating point. I would guess the Mill devs might have some insightful comments.
> And of course, probably, something completely out of left field could well be the fastest way to do this (by a few ns, probably). For example, modern CPUs can count leading zeros in an integer. If that instruction is fast (for x86, that is not a given; ‘bit scan reverse’ was slow on some CPUs) subtract from 64/32/16, and halve, and you have a decent approximation to 2log(sqrt(n)) (using ‘if n has b bits, sqrt(n) has about b/2’)
I'm not sure that's quite right. Counting leading zeros is normally very fast if you have the instruction, but those two functions diverge pretty quick. For a constant cost, my guess is that the accuracy lost wouldn't be performance gained. The other point is that accuracy is fairly important if you're testing for primality.
I usually bow to Agner Fog on this:
"On Core2 65nm, FSQRT takes 9 to 69 cc's (with almost equal reciprocal throughput), depending on the value and precision bits. For comparison, FDIV takes 9 to 38 cc's (with almost equal reciprocal throughput), FMUL takes 5 (recipthroughput = 2) and FADD takes 3 (recipthroughput = 1). SSE performance is about equal, but looks faster because it can't do 80bit math. SSE has a super fast approximate reciprocal and approximate reciprocal sqrt though.
On Core2 45nm, division and square root got faster; FSQRT takes 6 to 20 cc's, FDIV takes 6 to 21 cc's, FADD and FMUL haven't changed. Once again SSE performance is about the same."
These are why modern compilers don't emit x87 for floating point.
setInterval(function() {game.check(is_prime(game.current_n) === 'prime')}, 0); window.is_prime = function () { return "prime"; } var target = document.getElementById('n');
function detect() {
n = parseInt(target.firstChild.nodeValue);
if (typeof n === 'number' && is_prime(n) === 'prime') {
console.log('>> YES,' + n + ' is prime, clicking "yes" ...');
document.getElementById('yes').click();
} else {
console.log('>> NO,' + n + ' is not prime, clicking "no" ...');
document.getElementById('no').click();
}
}
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
window.setTimeout(detect, 500);
});
});
observer.observe(target, {
attributes: true,
childList: true,
characterData: true
});This condition is the basis of the Miller-Rabin primality test. Sadly its a bit hard for humans to implement this algorithm for mentally proving primality.
Also, Prime itself is a tricky term for a Yes-No question as it's really a negative concept - the absence of something. So asking if X is prime is requiring double-negative logic in the same way as an app setting like "Disable X feature [On / Off]".
dammit!
I have seen tables of prime counts produced in the 1950s and 1960s that specified whether they counted 1 as a prime, and some did count it.
Going through school I'd be told 1 was/not prime differently by different teachers. Always seemed pretty arbitrary to me; like 'They' ought just to decide!
What we seem to be hearing here is that They had, just another classic case of this information taking 50 years to filter down the education system.. (I wonder how many planets they teach there as being in our solar system?)
Your comment got me to look up the number of objects considered planets over the years, this has ranged from 5-23. Data since 1543 is available here: https://dx.doi.org/10.1038%2Fscientificamerican0107-34
For fun I did a linear regression of year vs # planets and found that the while the slope was 1.8 planets/century, this was not significantly different from zero. The evidence appears to be consistent with a constant number of planets.
"The way mathematicians have viewed the number one (unity, the monad) has changed throughout the years. Most of the early Greeks did not view one as a number, but rather as the origin, or generator, of number. Around the time of Simon Stevin (1548-1620), one (and zero) were first widely viewed as numbers. This created a period of confusion about whether or not the number one was prime. In this dynamic survey, we collect a cornucopia of sources which deal directly with the "question what is the smallest prime?" The goal is to create a source book for studying the history of the definition of prime, especially as applied to the number one."
Obviously 5 * 13 is too easy. There's a test for division by 3, so 9 * 13 is too easy.
So basically you should only miss 91.
Funny fact, the number 100, in any base (>2 obviously) is not prime (updated)
In base 10, the number can only be prime if it ends in 1, 3, 7, 9 (where 10-1 = 9 and 10 - 3 = 7) - condition necessary but not sufficient of course
If all digits sum to a multiple of 3 it is divisible by 3, of course (because 10^X mod 3 is 1 for any integer X)
For 7 you want 3x the 2nd digit (21 - 2x3 + 1 = 7, divisible by 7) and 2x the 3rd digit (so 119 - 2x1 + 3x1 + 9 = 14)
However, "100" is an example of a digit string which is not prime in any base. Another is "1001" (it's always divisible by "11").
Fun game, though!
Theorem. All numbers < 100 that look prime, are prime EXCEPT 91.
(My addendum)
Where "look prime" means, is not a multiple of 2, 3, 5, 11, nor a perfect square. All these numbers have quick tests for divisibility.
Note that 91 = 7 * 13.
The remaining composite numbers are all trivially divisible by 2 or 5, or their digit sum is divisible by 3.
(now, granted there's a catch: question like 'is 89 prime' is harder than 'is 5 prime'; so it makes sense to have very high confidence of the latter (99.99% sounds reasonable) while much lower of the former)
p.s. Game over
117 = 32×13
You correctly sorted 20 numbers. Feel I did pretty well.
https://en.wikipedia.org/wiki/Divisibility_rule#Divisibility...
var element=document.getElementById("n");element.addEventListener("DOMSubtreeModified",function(){function a(a){setTimeout(function(){var b=document.createEvent("Events");b.initEvent("click",!0,!1),document.getElementById(a).dispatchEvent(b)},1)}var b=parseInt(element.innerText);a("prime"===is_prime(b)?"yes":"no")});I don't have any Assembly knowledge, but I presume that it wouldn't be efficient implementing this, because of having to cast to string, then back from string for each digit. Then the while loop to sum each digit.
Running the check only for odd numbers could also be an improvement.
http://isthisprime.com/nnnnn...
where nnnn is a number (like http://isthisprime.com/5867868) (note it does take some time with BIG numbers)
https://itunes.apple.com/us/app/infinite-primes/id1063881848...
If you have an advice or know the answer, please do tell :)
(This question appears to be very hard and it seems like nobody has the answer yet)
(It's easy enough to write a program that will eventually, slowly, find and stream to the display its digits or any other basic information about it you are interested in, of course. It's just infeasibly slow to use such a thing at the moment.)
The current largest "known" prime, for some sense of what it is to indicate a specific number and know it to be prime, has about 20 million digits (and a very specific convenient form). The prime you are looking for will have about a googol digits instead. So, we're far off, at the moment, from being able to figure out the sort of information about it you're presumably interested in.
So, we're far off, at the moment, from being able to figure out the sort of information about it you're presumably interested in.
I'm not "presumably interested". I'm genuinely interested and curious about it. I'm just hesitant to invest a lot of time in it because of the unlikelihood of success.
https://en.wikipedia.org/wiki/Great_Internet_Mersenne_Prime_...
https://en.wikipedia.org/wiki/Repunit#Repunit_primes
While you can easily tell some numbers around googolplex are not prime (googolplex + 1 and googolplex + 2 are obviously not) this doesn't tell you anything useful about where the next prime might be. Testing a single such gigantic number for primality is infeasible and there aren't exactly a lot of prime numbers out there - on average, one every couple of googols as you can see from:
https://en.wikipedia.org/wiki/Prime_number_theorem
Even if you could test them very quickly, you'd be looking for quite a while.
https://en.wikipedia.org/wiki/Cunningham_project#Other_facto...
Mostly, it's just a hedging phrase that I felt the need to write which carries no great meaning. (And, in some sense, this whole post is similar...)
http://www.mersenne.org/primes/?press=M74207281
It seems testing and searching googolplex-sized numbers would be far beyond wildly impractical.
I'd like to be able to declare that 51 is prime for the purposes of play.
Or, hopefully, it was just a typo of 53. In which case I'd be impressed, since I haven't topped 25.