Wednesday, July 11, 2012

Project Euler Problem 10 (continued)

hahaha... I cheated in Project Euler. But as well I feel guilty, I tried to understand and built my own program. Even if the structure and solution is the same, at least I tried to understand how it solve very quickly.

First, let's review what is a prime number. Prime number, is a number that can only divide itself and 1. Exception would be 1, it wasn't considered prime number. 2 also is considered prime, and thus the only even number of prime number. Therefore, we can conclude almost all even number are not prime except 2, and all prime number except 2 are odd number, but not all odd number are prime number. We can brute strength programming, but as I had experienced, will take so much time, and may be wrong. Remember, there might be overflow, check your data type.

At larger scale or higher level, there is this sieve thing. Um, Sieve of Eratosthenes. I don't really understand it. But with some reading, it has something to do with square root of the number.

So, from the available solution in http://kahthong.com/2011/12/project-euler-problem-10 , I guess it works like this.
  1. It set the sum to 2, so the first prime number is already being included. in the link, the program use i=2. but it redundant, so I later change to 3. No use repeating the useless process.
  2. i%2 check for even number, and continue the loop instantly. This to eliminate 2 and its even 'siblings'.
  3. Then it start for 3 at the while() loop. This actually signal this program are similar to my prime function, but consider only the odd number, thus the reason for d+=2 iteration.
  4. Then there's the square root thing. I think, this actually a theory that simplify the calculation. The calculation or conditions checking will be reduced for some reason, and still within the range. This might be the real reason it almost just 1 second program speed. I am guessing trying to store every number until 2 million are not efficient way even if that's the theory. Creativity is not my strong point.
  5. it also loop until it reach the square root of the number. which is similar to the original prime function.
  6. last condition check for the primality after the, um... simplification above. if it match, add into the sum
  7. Then display it.
That's it, how I understand it.



*************************************************

No comments:

Post a Comment