Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • To check a number is perfect square or not using addition operation only.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 152
    Comment on it

    The problem is that a positive integer n is given and check if it is perfect square or not using only addition operation.

    // 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 and uses only addition operation.
    
    bool isPerfectSquare(int n)
    {
    	int sum=0;
    	for (int i=1; sum<n; i+=2)
    	{
    		sum += i;
    		if (sum == n)
    			return true;
    	}
    	return false;
    }
    
    int main()
    {
    	isPerfectSquare(90)? cout << "Yes\n": cout << "No\n";
    	isPerfectSquare(49)? cout << "Yes\n": cout << "No\n";
    	return 0;
    }
    

    Output:

    No
    Yes

    Explanation:

    The idea used in above program is that the sum of first n odd numbers is a perfect square. In this,from main a number is passed to isperfectsquare function which checks whether it is perfect square or not. Inside isperfectsquare a variable sum is initialized to 0, a for loop initializes a variable i to 0, for loop runs till passed n is greater than sum and i is incremented with 2. The function returns true if sum==n i.e sum of first odd numbers is equal to passed n else returns false. 

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: