Find the difference between the square of the sum and the sum of the squares of the first N natural numbers.
The square of the sum of the first ten natural numbers is (1 + 2 + ... + 10)² = 55² = 3025.
The sum of the squares of the first ten natural numbers is 1² + 2² + ... + 10² = 385.
Hence the difference between the square of the sum of the first ten natural numbers and the sum of the squares of the first ten natural numbers is 3025 - 385 = 2640.
You are not expected to discover an efficient solution to this yourself from first principles; research is allowed, indeed, encouraged. Finding the best algorithm for the problem is a key skill in software engineering.
For library documentation, follow Useful OCaml resources.
A Makefile
is provided with a default target to compile your solution and run the tests. At the command line, type:
make
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
The exercism/ocaml repository on GitHub is the home for all of the Ocaml exercises.
If you have feedback about an exercise, or want to help implementing a new one, head over there and create an issue or submit a PR. We welcome new contributors!
Problem 6 at Project Euler http://projecteuler.net/problem=6
open OUnit2
open Difference_of_squares
let ae exp got _test_ctxt = assert_equal exp got
let square_of_sum_tests = [
"square of sum 1" >::
ae 1 (square_of_sum 1);
"square of sum 5" >::
ae 225 (square_of_sum 5);
"square of sum 100" >::
ae 25502500 (square_of_sum 100);
]
let sum_of_squares_tests = [
"sum of squares 1" >::
ae 1 (sum_of_squares 1);
"sum of squares 5" >::
ae 55 (sum_of_squares 5);
"sum of squares 100" >::
ae 338350 (sum_of_squares 100);
]
let difference_of_squares_tests = [
"difference of squares 1" >::
ae 0 (difference_of_squares 1);
"difference of squares 5" >::
ae 170 (difference_of_squares 5);
"difference of squares 100" >::
ae 25164150 (difference_of_squares 100);
]
let () =
run_test_tt_main (
"difference of squares tests" >:::
List.concat [square_of_sum_tests; sum_of_squares_tests; difference_of_squares_tests]
)
let rec square_of_sum num acc =
match num = 0 with
| true ->
acc * acc
| false ->
square_of_sum (num - 1) (acc + num)
let square_of_sum num = square_of_sum num 0
let rec sum_of_squares num acc =
match num = 0 with
| true ->
acc
| false ->
sum_of_squares (num - 1) (acc + (num * num))
let sum_of_squares num = sum_of_squares num 0
let difference_of_squares num = square_of_sum num - sum_of_squares num
A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
Here are some questions to help you reflect on this solution and learn the most from it.
Level up your programming skills with 3,092 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors. Exercism is 100% free forever.
Sign up Learn More
Community comments