Square a number without *, / or pow()

Easy

Problem

Return n² without using multiplication, division or pow().

Example 1

Input:  n = 5
Output: 25

Example 2

Input:  n = -4
Output: 16

Also asked as: Calculate square of a number without using *, / and pow()

Test cases

Case 1

Input:    5
Expected: 25

Case 2

Input:    -4
Expected: 16

Case 3

Input:    1
Expected: 1

Case 4

Input:    0
Expected: 0

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. n² = sum of the first n odd numbers

Time O(n)Space O(1)

1 + 3 + 5 + … + (2n−1) = n². Add n odd numbers.

function square(n) {
n = Math.abs(n);
let result = 0;
for (let i = 0; i < n; i++) result += 2 * i + 1;
return result;
}

O(log n) via bit shifts: square(n) = (square(n>>1) << 2) + (n odd ? (n<<1) - 1 : 0).