Trusted answers to developer questions

Ravi

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`

- 1
^{2}= 1 - 2
^{2}= (1 + 3) = 4 - 3
^{2}= (1 + 3 + 5 = 9) - 4
^{2}= (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.

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

- 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`

.

RELATED TAGS

java

CONTRIBUTOR

Ravi

RELATED COURSES

View all Courses

Keep Exploring

Related Courses