Overview
This VI shows how to solve Project Euler Problem #6.
Description
Project Euler Problem #6:
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
Requirements
Steps to Implement or Execute Code
Additional Information or References
**This document has been updated to meet the current required format for the NI Code Exchange.**
Example code from the Example Code Exchange in the NI Community is licensed with the MIT license.
What is the Add with 0 for? That should probably be removed.
I would also combine the two loops into one.
Otherwise, this is a pretty straight forward problem. Looks pretty good.
To save memory it is also possible to use a shift register an compute the two sum "run-time" to avoid unnecessary memory allocation.
Run one extra iteration of the loop is used to remove the "+1" inside the loop.
Loops can be joined as noted crossrulz. 🙂
Did you do any benchmarking to see if that is really faster to use the shift registers? I was considering that as well, just was debating if it would actually come out faster.
I run both "core" code (while loop excluded) 10'000'000 times to get an overall execution time in the order of seconds.
The "optimized" version turn out to be 3.4 time faster. In a real application this can make a huge difference!
That's actually more of a difference than I was initially expecting. But the more I think about it, the more it makes sense, especially as N becomes really big (large array = large memory => slow loops).
There is a formula for the sum of all integers 1..N. It is N(N+1)/2
There is a formula for the sum of the squares of all integers 1..N. It is N(N+1)(2N+1)/6.
Square the first formula and then subtract the second one to get (N(N+1)/2)^2 - N(N+1)(2N+1)/6. (And I be that can be simplified some....)
This will compute faster than the loops. Loop solutions are BigO(N). Formulaic solution is BigO(1).