How to find the square of a number in Java

Problem statement

Find the square of an integer without using the division or multiplication operators. Additionally, it is forbidden to use the power function included in any programming language library.

Example 1

  • Input: n=8
  • Output: 64

Example 2

  • Input: n=10
  • Output: 100

Solution

  • 12 = 1
  • 22 = (1 + 3) = 4
  • 32 = (1 + 3 + 5 = 9)
  • 42 = (1 + 3 + 5 + 7) = 16

Looking at the above sequence, we can see a pattern emerge. The pattern is based on the fact that an integer n's square root can be found by adding odd numbers precisely n times.

Code

public class Main{
public static int findSquareOfN(int n) {
int odd = 1;
int square = 0;
n = Math.abs(n);
while (n-- > 0) {
square += odd;
odd = odd + 2;
}
return square;
}
public static void main(String[] args) {
int n=15;
System.out.println("The square of " + n + " is " + findSquareOfN(n));
}
}
Find the square of a number in Java

Explanation

  • Lines 3–15: We define the findSquareOfN() method. This implements the algorithm defined in the solution above to find the square of a number.
  • Line 18: We define n.
  • Line 19: We invoke findSquareOfN() to find the square of n.
New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources