Perfect Square: In mathematics, a square number, sometimes also called a perfect square, is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 9 is a square number, since it can be written as 3?×?3. (Text from Wikipedia)
We are going to write a program that checks if the input
number is a perfect square or not. C Program to check Perfect Square using sqrt() function: We can perform the same program getting help from sqrt() function. The sqrt() function is bundled with math.h header file. Here is the program: /* C Program to check Perfect Square using sqrt function */ #include <stdio.h> #include <math.h> int main( { int n, temp; printf("Enter a number: "); scanf("%d",&n); temp = sqrt(n); if(temp*temp == n) printf("YES."); else printf("NO."); return 0; }
In this example, we will see a C program through which we can check if a given number is a perfect square or not. If a whole number is the square of another whole number then it is known as a perfect square, like 16 is the square of 4 so 16 will be called a Perfect square. Algorithm:
Output: Enter an integer number: 64 64 is a perfect square. Given a number, check if it is a perfect square or not. Input : 2500 Output : Yes Explanation: 2500 is a perfect square. 50 * 50 = 2500 Input : 2555 Output : No
Time Complexity: O(log(x)) To know more about the inbuilt sqrt function, refer this Stackoverflow and this StackExchange threads.
Time Complexity : O(sqrt(n)) |