Project Euler/6
From charlesreid1
The problem: https://projecteuler.net/problem=6
The solution: https://git.charlesreid1.com/cs/euler/src/master/006/Problem006.java
Project Euler Problem 6
The sum of the squares of the first 10 integers is 385.
The square of the sum of the first 10 integers is 3025.
Their difference is 3025 - 385 = 2640.
Find this for the first 100 integers.
Project Euler Link: https://projecteuler.net/problem=6
Link to solution, git.charlesreid1.com: https://git.charlesreid1.com/cs/euler/src/master/Problem006.java
Principle: this utilizes two summations that are useful to know off the top of your head. If you do, it makes this an O(1) problem. If not, it makes it an O(N) problem.
The two summations are:
and
Going a bit further, these two formulas can be combined to get an expression for the difference:
Now this can be written as a single fraction by getting a common denominator of 24, which yields:
This gives a final expression for the difference as:
Code Implementations
The implementations of the above formulas in Java:
/** Formula for the sum of the square of integers up to N. */ public static int sum_of_squares(int n) { int result = (n*(n+1)*(2*n+1))/6; return result; } /** Formula for the sum of the integers up to N, squared. */ public static int square_of_sum(int n) { int result = (n*(n+1))/2; result *= result; return result; }
The generalization
This exercise links in with the pythagorean theorem, the binomial theorem, and the misconception that many students in algebra have about the rules for distributing exponents.
Flags
Project Euler project euler notes
Round 1: Problems 1-20 Problem 1 · Problem 2 · Problem 3 · Problem 4 · Problem 5 · Problem 6 · Problem 7 · Problem 8 · Problem 9 · Problem 10 Problem 11 · Problem 12 · Problem 13 · Problem 14 · Problem 15 · Problem 16 · Problem 17 · Problem 18 · Problem 19 · Problem 20 Round 2: Problems 50-70 Problem 51 · Problem 52 · Problem 53 · Problem 54 · Problem 55 · Problem 56 · Problem 57 · Problem 58 · ... · Problem 61 · Problem 62 · Problem 63 · Problem 64 · Problem 65 · Problem 66 · Problem 67 Round 3: Problems 100-110 Problem 100 · Problem 101 · Problem 102 Round 4: Problems 500-510 Problem 500 · Problem 501 * · Problem 502 * Round 5: Problems 150-160 Round 6: Problems 250-260 Round 7: Problems 170-180
|