Given a natural number ‘n’, print squares of first n natural numbers without using *, / and -.
Input: n = 5
Output: 0 1 4 9 16
Method 1: The idea is to calculate next square using previous square value. Consider the following relation between square of x and (x-1). We know square of (x-1) is (x-1)2 – 2*x + 1. We can write x2 as
x2 = (x-1)2 + 2*x - 1
x2 = (x-1)2 + x + (x - 1)
When writing an iterative program, we can keep track of previous value of x and add the current and previous values of x to current value of square. This way we don’t even use the ‘-’ operator.
void
printSquares(
int
n)
{
// Initialize 'square' and previous value of 'x'
int
square = 0, prev_x = 0;
// Calculate and print squares
for
(
int
x = 0; x < n; x++)
{
// Update value of square using previous value
square = (square + x + prev_x);
// Print square and update prev for next iteration
cout << square <<
" "
;
prev_x = x;
}
}
void
printSquares(
int
n)
{
// Initialize 'square' and first odd number
int
square = 0, odd = 1;
// Calculate and print squares
for
(
int
x = 0; x < n; x++)
{
// Print square
cout << square <<
" "
;
// Update 'square' and 'odd'
square = square + odd;
odd = odd + 2;
}
}