Given an integer N, the task is to find its perfect square root by repeated subtraction only.
Examples:
Input: N = 25
Output: 5
Input: N = 841
Output: 29
Babylonian Method and Binary Search Approach: Refer to Square root of an integer for the approaches based on Babylonian Method and Binary Search.
Repeated Subtraction Approach:
Follow the steps below to solve the problem:
- Sum of the first N odd natural numbers is equal to N2.
- Based on the fact mentioned above, repetitive subtraction of odd numbers starting from 1, until N becomes 0 needs to be performed.
- The count of odd numbers, used in this process, will give the square root of the number N.
Illustration:
N = 81
Step 1: 81-1=80
Step 2: 80-3=77
Step 3: 77-5=72
Step 4: 72-7=65
Step 5: 65-9=56
Step 6: 56-11=45
Step 7: 45-13=32
Step 8: 32-15=17
Step 9: 17-17=0
Since, 9 odd numbers were used, hence the square root of 81 is 9.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int SquareRoot( int num)
{
int count = 0;
for ( int n = 1; n <= num; n += 2) {
num = num - n;
count += 1;
if (num == 0)
break ;
}
return count;
}
int main()
{
int N = 81;
cout << SquareRoot(N);
}
|
Java
class GFG{
public static int SquareRoot( int num)
{
int count = 0 ;
for ( int n = 1 ; n <= num; n += 2 )
{
num = num - n;
count += 1 ;
if (num == 0 )
break ;
}
return count;
}
public static void main(String[] args)
{
int N = 81 ;
System.out.println(SquareRoot(N));
}
}
|
Python3
def SquareRoot(num):
count = 0
for n in range ( 1 , num + 1 , 2 ):
num = num - n
count = count + 1
if (num = = 0 ):
break
return count
N = 81
print (SquareRoot(N))
|
C#
using System;
class GFG{
public static int SquareRoot( int num)
{
int count = 0;
for ( int n = 1; n <= num; n += 2)
{
num = num - n;
count += 1;
if (num == 0)
break ;
}
return count;
}
public static void Main()
{
int N = 81;
Console.Write(SquareRoot(N));
}
}
|
Javascript
<script>
function SquareRoot(num)
{
let count = 0;
for (let n = 1; n <= num; n += 2) {
num = num - n;
count += 1;
if (num == 0)
break ;
}
return count;
}
let N = 81;
document.write(SquareRoot(N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
02 Mar, 2021
Like Article
Save Article