Friday, July 3, 2015

Project Euler 7: 10,001 prime number (Java)

This one is interesting, if you think about it.. question is if there is a formula?

Well.. I looked for a formula for it and according to my favies wikipedia: "In number theory, a formula for primes is a formula generating the prime numbers, exactly and without exception. No such formula which is efficiently computable is known. A number of constraints are known, showing what such a "formula" can and cannot be.".. so "efficiently" iterate it is! You could iterate yourself to death going through every possibility.. or try and find a better way to iterate, just less.

I figured.. welp. Let's say we have the number 100. It breaks down into 1 x 100, 2 x 50, 4 x 25, 5 x 20, 10 x 10.. and stops there. The first number always goes up, second one always goes down. If they meet, they reverse.. and we are repeating ourselves. BUT you can try this, no matter what .. at least one of the pair of numbers is less than half. So we will ALWAYS catch the pair of multiples if we check all the numbers up to half. So what I am doing for example 100 is seeing if any number from 1-50 will divide evenly into it. The minute its divisible by any of those numbers iterating from 1 to 50, its not prime, doesn't get added to my magic list of numbers, and the loop continues to check 101.. and so on.

1031 ms to calculate is about a second, which fits into most of your attention spans out there.. so I'll take it :).

Point to note and something that was COOL. You can use (int)Math.ceil(num/2.0) to get a rounded up version of your number (ceil = ceiling, you can do Math.floor to get it rounded down.. floor is down whee). BAD thing. Don't forget your cast depending on the type of numbers being used!!!


104743 is the solution calculated in a time of 1031ms.