Thursday, July 4, 2024
HomeData ModellingData Structure & AlgorithmCheck perfect square using addition/subtraction

Check perfect square using addition/subtraction

Given a positive integer n, check if it is perfect square or not using only addition/subtraction operations and in minimum time complexity.
We strongly recommend you to minimize your browser and try this yourself first.
We can use the property of odd number for this purpose: 

Addition of first n odd numbers is always perfect square 
1 + 3 = 4,      
1 + 3 + 5 = 9,     
1 + 3 + 5 + 7 + 9 + 11 = 36 ...

Below is the implementation of above idea : 

C++




// C++ program to check if n is perfect square
// or not
#include <bits/stdc++.h>
 
using namespace std;
 
// This function returns true if n is
// perfect square, else false
bool isPerfectSquare(int n)
{
    // sum is sum of all odd numbers. i is
    // used one by one hold odd numbers
    for (int sum = 0, i = 1; sum < n; i += 2) {
        sum += i;
        if (sum == n)
            return true;
    }
    return false;
}
 
// Driver code
int main()
{
    isPerfectSquare(35) ? cout << "Yes\n" : cout << "No\n";
    isPerfectSquare(49) ? cout << "Yes\n" : cout << "No\n";
    return 0;
}


Java




// Java program to check if n
// is perfect square or not
 
public class GFG {
 
    // This function returns true if n
    // is perfect square, else false
    static boolean isPerfectSquare(int n)
    {
        // sum is sum of all odd numbers. i is
        // used one by one hold odd numbers
        for (int sum = 0, i = 1; sum < n; i += 2) {
            sum += i;
            if (sum == n)
                return true;
        }
        return false;
    }
 
    // Driver Code
    public static void main(String args[])
    {
 
        if (isPerfectSquare(35))
            System.out.println("Yes");
        else
            System.out.println("NO");
 
        if (isPerfectSquare(49))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by Sam007


Python3




# This function returns true if n is
# perfect square, else false
def isPerfectSquare(n):
 
    # the_sum is sum of all odd numbers. i is
    # used one by one hold odd numbers
    i = 1
    the_sum = 0
    while the_sum < n:
        the_sum += i
        if the_sum == n:
            return True
        i += 2
    return False
 
# Driver code
if __name__ == "__main__":
    print('Yes') if isPerfectSquare(35) else print('NO')
    print('Yes') if isPerfectSquare(49) else print('NO')
 
# This code works only in Python 3


C#




// C# program to check if n
// is perfect square or not
using System;
 
public class GFG {
 
    // This function returns true if n
    // is perfect square, else false
    static bool isPerfectSquare(int n)
    {
        // sum is sum of all odd numbers. i is
        // used one by one hold odd numbers
        for (int sum = 0, i = 1; sum < n; i += 2) {
            sum += i;
            if (sum == n)
                return true;
        }
        return false;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
 
        if (isPerfectSquare(35))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
 
        if (isPerfectSquare(49))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code is contributed by Sam007.


PHP




<?php
// PHP program to check if n is
// perfect square or not
 
// This function returns true if n is
// perfect square, else false
function isPerfectSquare($n)
{
    // sum is sum of all odd numbers.
    // i is used one by one hold odd
    // numbers
    for ( $sum = 0, $i = 1; $sum < $n;
                              $i += 2)
    {
        $sum += $i;
        if ($sum == $n)
            return true;
    }
     
    return false;
}
 
// Driver code
if(isPerfectSquare(35))
    echo "Yes\n";
else
    echo "No\n";
     
if(isPerfectSquare(49))
    echo "Yes\n";
else
    echo "No\n";
 
// This code is contributed by ajit.
?>


Javascript




<script>
 
// JavaScript program to check if n
// is perfect square or not
 
    // This function returns true if n
    // is perfect square, else false
    function isPerfectSquare(n)
    {
        // sum is sum of all odd numbers. i is
        // used one by one hold odd numbers
        for (let sum = 0, i = 1; sum < n; i += 2) {
            sum += i;
            if (sum == n)
                return true;
        }
        return false;
    }
 
// Driver Code
 
        if (isPerfectSquare(35))
           document.write("Yes" + "<br/>");
        else
            document.write("NO" + "<br/>");
  
        if (isPerfectSquare(49))
            document.write("Yes" + "<br/>");
        else
            document.write("No" + "<br/>");
     
    // This code is contributed by target_2.
</script>


Output : 

No
Yes

Time Complexity: O(n)

Auxiliary Space: O(1)
How does this work? 
Below is explanation of above approach. 

1 + 3 + 5 + ...  (2n-1) = (2*i - 1) where 1<=i<=n
                        = 2*i - 1  where 1<=i<=n
                        = 2n(n+1)/2 - n
                        = n(n+1) - n
                        = n2

Reference: 
https://www.neveropen.co.za/sum-first-n-odd-numbers-o1-complexity/ 
http://blog.jgc.org/2008/02/sum-of-first-n-odd-numbers-is-always.html
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

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 neveropen!

Nango Kalahttps://www.kala.co.za
Experienced Support Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Microsoft Excel, Customer Service, Microsoft Word, Technical Support, and Microsoft Office. Strong information technology professional with a Microsoft Certificate Solutions Expert (Privet Cloud) focused in Information Technology from Broadband Collage Of Technology.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments