Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print the Non Square Numbers in C
In C programming, a perfect square is an integer that is the square of another integer. For example, 1, 4, 9, 16, 25 are perfect squares because they equal 1², 2², 3², 4², 5² respectively. Non-square numbers are all other positive integers that are not perfect squares.
Syntax
#include <math.h> int sqrt(double x); // Returns square root of x
Perfect Square Numbers
The first few perfect squares are −
1, 4, 9, 16, 25, 36, 49, 64, 81, 100
These correspond to −
1² = 1, 2² = 4, 3² = 9, 4² = 16, 5² = 25 6² = 36, 7² = 49, 8² = 64, 9² = 81, 10² = 100
Non-Square Numbers
Non-square numbers are all positive integers that are not perfect squares −
2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26...
Algorithm
To identify non-square numbers −
- For each number from 1 to the user-specified limit
- Calculate its square root using
sqrt()function - Check if squaring the integer part gives back the original number
- If not, it's a non-square number
Example: Print Non-Square Numbers
#include <stdio.h>
#include <math.h>
int main() {
int limit, i, sqrtValue;
int count = 0;
printf("Print the Non Square Numbers till: ");
scanf("%d", &limit);
printf("The Non Square Numbers are:
");
for(i = 1; count < limit; i++) {
sqrtValue = (int)sqrt(i);
if(i != sqrtValue * sqrtValue) {
printf("%d\t", i);
count++;
}
}
printf("
");
return 0;
}
Print the Non Square Numbers till: 15 The Non Square Numbers are: 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19
How It Works
The program uses the sqrt() function to find the square root of each number. By casting the result to an integer, we get the floor value. If squaring this integer doesn't equal the original number, then the original number is not a perfect square.
Conclusion
Non-square numbers can be identified by checking if a number's square root, when squared again, returns the original number. This method efficiently determines which numbers are not perfect squares within any given range.
