Retour aux défis
Facile 0 résolus 0 % de réussite

Difference of Squares

Subtract the sum of squares from the square of the sum.

Ce que vous allez apprendre

  • Compute sums of numbers and of squares
  • Use closed formulas instead of loops
  • Compare two ways to get the same answer

Problème

Afficher la traduction

Using the integers from 1 through n, calculate two quantities: first add the integers and square the result; separately square each integer and add those squares. Return the first quantity minus the second.

Implement difference_of_squares(n).

Input

n: The last integer to include.

Output

Return square-of-sum minus sum-of-squares.

Contraintes

0 ≤ n ≤ 50,000. For n = 0, both sums are 0. All required values fit signed 64-bit integers.

Exemples

Exemple 1
Entrée :
n = 4

Sortie attendue :
expected = 70
Entrée :
long long n = 4;

Sortie attendue :
long long expected = 70;
Entrée :
long n = 4;

Sortie attendue :
long expected = 70;

Explication

(1 + 2 + 3 + 4)² = 100. The sum of squares is 1 + 4 + 9 + 16 = 30. Subtract: 100 − 30 = 70.

Exemple 2
Entrée :
n = 1

Sortie attendue :
expected = 0
Entrée :
long long n = 1;

Sortie attendue :
long long expected = 0;
Entrée :
long n = 1;

Sortie attendue :
long expected = 0;

Explication

Both quantities equal 1, so their difference is 0.

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

You are comparing two summaries of the same range: one based on summing first, the other based on squaring first.

Indice 2

Use the closed-form expressions for sums of integers and sums of squares instead of looping through every value.

Indice 3

Handle the zero case carefully, since both quantities should be zero there.

Complexité attendue

O(1) time, O(1) extra space

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.