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 ofn.