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
n=8
64
Example 2
n=10
100
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.
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));}}
findSquareOfN()
method. This implements the algorithm defined in the solution above to find the square of a number.n
.findSquareOfN()
to find the square of n
.