Python program to calculate square of a given number
Last Updated :
06 Dec, 2023
Given a number, the task is to write a Python program to calculate the square of the given number. In this article, we will see how to square in Python.
Example:
Input: 4
Output: 16
Input: 3
Output: 9
Input: 10
Output: 100
Square of a Given Number in Python
We will provide the number, and we will get the square of that number as output. We have three ways to do so:
Calculating Square of a Number Using Multiplication
In this approach, we will multiply the number with one another to get the square of the number. In this example, a variable n
is assigned the value 4, and its square is calculated by multiplying it by itself. The result is then printed, yielding the square of 4, which is 16.
Python3
n = 4
square = n * n
print (square)
|
Output:
16
Python Calcluate a Number Square Using Exponent Operator
In this approach, we use the exponent operator to find the square of the number.
Exponent Operator: **
Return: a ** b will return a raised to power b as output.
In this example, a variable n
is assigned the value 4, and its square is calculated using the exponent operator **
, resulting in the square of n
. The computed square, 16, is then printed. In this way we can square in Python.
Python3
n = 4
square = n * * 2
print (square)
|
Output:
16
Squaring a Number Using pow() Method
In this approach, we will use the pow() method to find the square of the number. This function computes x**y and returns a float value as output.
Syntax: float pow(x,y)
Parameters :
x : Number whose power has to be calculated.
y : Value raised to compute power.
Returns: Returns the value x**y in float.
In this example, the variable n
is assigned the value 4, and its square is calculated using the pow
method with arguments n
and 2
. The resulting square, 16, is then printed.
Python3
n = 4
square = pow (n, 2 )
print (square)
|
Output:
16.0
Python Squaring a Number Using operator.pow() method
In this example, a variable n
is assigned the value 4, and its square is calculated using the pow
method from the operator
module with arguments n
and 2
. The computed square, 16, is then printed.
Python3
n = 4
import operator
square = operator. pow (n, 2 )
print (square)
|
Time Complexity : O(N)
Auxiliary Space : O(1)
Calculating Square a Number Using bitwise Operators
This method uses the bitwise left shift operator (<<) to multiply the number by 2, effectively finding the square of the number.
Python3
n = 4
square = n << 1
print (square)
|
Time complexity: O(1)
Auxiliary space: O(1) as it only uses a single variable to store the result.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...