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 :
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
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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if a number is a perfect square having all its digits as a perfect square
- Check if a number is perfect square without finding square root
- Count numbers upto N which are both perfect square and perfect cube
- Check if a given number is a Perfect square using Binary Search
- Check if given number is perfect square
- Check if product of array containing prime numbers is a perfect square
- Check whether the number can be made perfect square after adding K
- Check if the sum of a subarray within a given range is a perfect square or not
- Find minimum number to be divided to make a number a perfect square
- Number of times the largest perfect square number can be subtracted from N
- Perfect Square String
- Largest number that is not a perfect square
- Permutation of numbers such that sum of two consecutive numbers is a perfect square
- Minimum digits to remove to make a number Perfect Square
- Find the Next perfect square greater than a given number
- Largest factor of a given number which is a perfect square
- Count of pairs in an array whose sum is a perfect square
- Largest perfect square number in an Array
- Largest Divisor of a Number not divisible by a perfect square
- Closest perfect square and its distance