From 19f0270202465a99ea2f588a262d453b789e39e6 Mon Sep 17 00:00:00 2001 From: Alexander Heldt Date: Sat, 1 Nov 2025 11:51:57 +0100 Subject: [PATCH] difference-of-squares v2 --- .../src/difference_of_squares.gleam | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/difference-of-squares/src/difference_of_squares.gleam b/difference-of-squares/src/difference_of_squares.gleam index feb3ad2..cbdbb82 100644 --- a/difference-of-squares/src/difference_of_squares.gleam +++ b/difference-of-squares/src/difference_of_squares.gleam @@ -1,14 +1,25 @@ pub fn square_of_sum(n: Int) -> Int { - let sum = sum_to(n) - sum * sum + // (1 + 2 + ... n)^2 + square_of_sum_loop(n, 0) } -fn sum_to(n: Int) -> Int { - n * { n + 1 } / 2 +fn square_of_sum_loop(n: Int, acc: Int) -> Int { + case n { + 0 -> acc * acc + _ -> square_of_sum_loop(n - 1, acc + n) + } } pub fn sum_of_squares(n: Int) -> Int { - n * { n + 1 } * { 2 * n + 1 } / 6 + // TODO (1^2 + 2^2 ... + n^2) + sum_of_squares_loop(n, 0) +} + +fn sum_of_squares_loop(n: Int, acc: Int) -> Int { + case n { + 0 -> acc + _ -> sum_of_squares_loop(n - 1, acc + { n * n }) + } } pub fn difference(n: Int) -> Int {