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.
Makefile is provided with a default target to compile your solution and run the tests. At the command line, type:
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 square_of_sum n = n * n * (n+1) * (n+1) / 4 let sum_of_squares n = n * (n+1) * (2 * n + 1) / 6 let difference_of_squares n = square_of_sum n - sum_of_squares n
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.