exercism

Exercism - Difference of Squares

This post shows you how to get Difference of Squares exercise of Exercism.

Stevinator Stevinator
6 min read
SHARE
exercism dart flutter difference-of-squares

Preparation

Before we click on our next exercise, let’s see what concepts of DART we need to consider

Difference of Squares Exercise

So we need to use the following concepts.

List.generate

The List.generate method creates a list of a specified length by calling a function for each index. It’s perfect for creating sequences of numbers.

void main() {
  // Generate list of numbers 1 to 10
  List<int> numbers = List<int>.generate(10, (x) => x + 1);
  print(numbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  
  // Generate list of squares
  List<int> squares = List<int>.generate(5, (x) => (x + 1) * (x + 1));
  print(squares); // [1, 4, 9, 16, 25]
}

Reduce Method

The reduce method combines all elements of a collection into a single value using a provided function. It’s useful for summing numbers or finding maximum/minimum values.

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  
  // Sum all numbers
  int sum = numbers.reduce((prev, curr) => prev + curr);
  print(sum); // 15
  
  // Find maximum
  int max = numbers.reduce((prev, curr) => prev > curr ? prev : curr);
  print(max); // 5
}

Power Function (pow)

The pow function from dart:math raises a number to a given power. It returns a num type, so you may need to convert it to int using toInt().

import 'dart:math';

void main() {
  // Square a number (raise to power of 2)
  num result = pow(5, 2);
  print(result); // 25.0
  
  // Convert to int
  int square = pow(5, 2).toInt();
  print(square); // 25
  
  // Cube a number (raise to power of 3)
  int cube = pow(3, 3).toInt();
  print(cube); // 27
}

Arithmetic Operations

Basic arithmetic operations in Dart include addition (+), subtraction (-), multiplication (*), and division (/).

void main() {
  int a = 10;
  int b = 5;
  
  print(a + b); // 15 (addition)
  print(a - b); // 5 (subtraction)
  print(a * b); // 50 (multiplication)
  print(a / b); // 2.0 (division, returns double)
  print(a ~/ b); // 2 (integer division)
}

Expression Bodied Methods

When we have a method with one code line, we can use this concept to keep our code tidy.

class Calculator {
  int add(int a, int b) => a + b;
  int multiply(int a, int b) => a * b;
}

Introduction

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.

What is the difference of squares?

The difference of squares is a mathematical concept that involves finding the difference between two squared values. In this exercise, we’re finding the difference between:

  • The square of the sum of natural numbers: (1 + 2 + … + n)²
  • The sum of the squares of natural numbers: 1² + 2² + … + n²

This problem demonstrates how different mathematical operations (summing then squaring vs squaring then summing) produce different results.

— Mathematics

How can we calculate the difference of squares?

To calculate the difference of squares for the first N natural numbers:

  1. Square of Sum:

    • Sum all numbers from 1 to N: 1 + 2 + … + N
    • Square the result: (sum)²
  2. Sum of Squares:

    • Square each number from 1 to N: 1², 2², …, N²
    • Sum all the squares: 1² + 2² + … + N²
  3. Difference:

    • Subtract the sum of squares from the square of sum

For example, with N = 10:

  • Square of sum: (1 + 2 + … + 10)² = 55² = 3025
  • Sum of squares: 1² + 2² + … + 10² = 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 + 81 + 100 = 385
  • Difference: 3025 - 385 = 2640

Solution

import "dart:math";

class DifferenceOfSquares {
  int squareOfSum(int n) => pow(List<int>.generate(n, (x) => x+1).reduce((prev,curr) => prev+curr),2).toInt();

  int sumOfSquares(int n) => List<int>.generate(n, (x) => pow(x+1, 2).toInt()).reduce((p,c) => p+c);

  int differenceOfSquares(int n) => squareOfSum(n) - sumOfSquares(n);
}

Let’s break down the solution:

  1. squareOfSum(int n) - Calculates the square of the sum:

    • List<int>.generate(n, (x) => x+1) - Creates a list [1, 2, 3, …, n]
    • .reduce((prev,curr) => prev+curr) - Sums all numbers in the list
    • pow(..., 2) - Squares the sum
    • .toInt() - Converts the result to an integer
  2. sumOfSquares(int n) - Calculates the sum of squares:

    • List<int>.generate(n, (x) => pow(x+1, 2).toInt()) - Creates a list of squares [1², 2², 3², …, n²]
    • .reduce((p,c) => p+c) - Sums all the squares
  3. differenceOfSquares(int n) - Calculates the difference:

    • Simply subtracts sumOfSquares(n) from squareOfSum(n)

The solution uses expression-bodied methods to keep the code concise and readable, leveraging Dart’s functional programming capabilities with generate and reduce.


You can watch this tutorial on YouTube. So don’t forget to like and subscribe. 😉

Watch on YouTube
Stevinator

Stevinator

Stevinator is a software engineer passionate about clean code and best practices. Loves sharing knowledge with the developer community.