Python program to print non square numbers
In this tutorial, we will see how to print non square numbers in Python.
Non square numbers are the numbers which are not the perfect squares of any number. When any number is multiplied with itself, it results into a square number. Vice versa of the same is a non square number. For instance, 4 is a square number since it can be written as 2 x 2 whereas 3 is a non square number. Some more examples of non square numbers are: 2, 3, 5, 6, 7, 8, 10.
In this module, we will learn to print non square numbers in python within the range provided by the user. Before getting on to the actual code, let us first understand math module in python. The math module is a readily available standard module in python which gives access to various mathematical functions for performing mathematical operations. To use this module, we have to import it into our python file using,
Some mathematical functions that math module in python gives access to are: exp(x), pow(x,y), log10(x), sqrt(x), etc. In this module, we will use the sqrt(x) function. It is an inbuilt function that returns the square root of any given number. Syntax:
Printing non square numbers in python
Problem statement: Write a program to print non square numbers in python.
Logic: Take square root of any number. If that root when multiplied by itself gives the original number, then it is a square number and hence it should not be printed.
- Import the math module.
- Accept the range (n) from the user till which the non square number is to be printed from 0.
- Inside the for loop, ranging from 0 to n, calculate square root of the number using sqrt() function.
- If the root when multiplied with itself gives the original number, then increment it by 1 and check for that number.
- Else, print the number.
import math print("Enter the range: ") n = int(input()) for i in range(0, n): root = int(math.sqrt(i)) if i == root*root: i = i + 1 else: print(i)
Enter the range: 9 2 3 5 6 7 8
Hence, we have successfully printed non-square numbers within the range provided by the user.
NOTE: There maybe other possible methods to solve this problem.
You may also read: