How to display square root if 50 as 5√2 in python - python

I am writing a program to output square root of an number in python. My current code looks like:
import math
num = int(input("Enter the number for which you want the square root"))
if math.floor(math.sqrt(num)) == math.ceil(math.sqrt(num)):
v = math.sqrt(num)
print(f"The given number is perfect square and the square root is {v} ")
elif num <0:
print("The square root of the given number is imaginary")
else:
print(f"The square root of the given number is \u221A{num}")
#\u221A is unicode for square root symbol
My current program checks if the entered number is perfect square then displays the square root. if it is not a perfect square it just displays √num. For example if num is 300, it will display √300. But i want it to display it as 10√3. Any ideas about how do i do that. I dont want any decimals in my result.

You can use sympy:
import sympy
sympy.init_printing(use_unicode=True)
sympy.sqrt(300)
Output:
10√3

You could find the largest root that is a divisor of your number and present the remainder as the √xxx part:
def root(N):
for r in range(int(N**0.5)+1,1,-1):
if N % (r*r) == 0:
n = N // (r*r)
return str(r) + f"√{n}"*(n>1)
return f"√{N}"
print(root(50)) # 5√2
print(root(81)) # 9
print(root(96)) # 4√6
print(root(97)) # √97

Related

making a while loop to output list of perfect squared numbers

I'm trying to make a while loop that displays all possible perfect squared numbers up to the value is provided by the user input
Below is the code that I have produced for this however this only display the next possible perfect squared number
num = input("Type in a positive whole number: ")
count = 0
square = 0
while square <= num:
count = count + 1
square = count*count
print square
Using Python 3 syntax:
Convert input to int and use a list comprehension like so:
num = int(input("Type in a positive whole number: "))
print([i*i for i in range(int(num**0.5) + 1)])

logical mistake while checking integer

i was just writing a code to check whether a number is a perfect square and encountered an issue - the code is workin only for '4' , for example if entered number is 36, when i reaches the value 6, i**i is found to be 6*36- i mean i possesses different values there
n=int(input('Enter an integer '))
x=0
for i in range(1,n+1):
if (i**i)==n:
print('you entered a perfect square ',i,'^',i,'=',n)
else:
x=x+1
if x==n:
print('you didnt enter a perfect square ')
i dont want any edits to my logic - somebody pls improve the same code
In Python, i**i means i^i, but to check if the given number is a perfect square or not, you need to check if i**2 == n. With your logic, we don't need to check for numbers which are more than sqrt(n). If you use a function, code will be much easier to debug. So an improved version will be:
from math import sqrt
def is_perf_sq(n):
for i in range(1, int(sqrt(n))+1):
if i**2 == n:
return 'You entered a perfect square '+ str(i) + '^ 2 =' + str(n)
return str(n) + ' is not a perfect square'
n = int(input('Enter an integer:').strip())
print(is_perf_sq(n))
Run time improvement:
You don't need to check for all number and square and check them, you just need the square root of that number. Then add 0.5 to it and square the integer part, if we get back the number then it's a perfect square otherwise not. So the code will be then:
from math import sqrt
n = int(input('Enter an integer:'))
if int(sqrt(n)+0.5)**2 == n:
print(n, 'is a perfect square')
else:
print(n, 'is not a perfect square')
change the line
if (i**i)==n:
to
if (i*i) == n:

How to find out if a number is a perfect square without using sqrt function or ** in Python? [duplicate]

This question already has answers here:
Check if a number is a perfect square
(25 answers)
Closed 4 days ago.
I have to write a program that finds out whether or not a number is a perfect square. The terms are I don't use a sqrt function or an exponent (**)
I previously showed my teacher my solution using exponent (**) and she told me not to include that there.
num=int(input("Enter a positive integer: "))
base=1
while num/base!=base:
base=base+1
if (num/base)%1==0:
print(num,"is a square")
else:
print(num,"is not a square")
It works fine with perfect squares but when they're not, it won't work because I can't find a way to get it out of the while loop even though it's not a perfect square.
You have to change
while num/base!=base:
to
while num/base>base:
and it will work.
You can iterate till finding a value bigger than you number:
You are sure the while will finish since you have a strictly increasing sequence.
def is_perfect_square(x):
i = 1
while i*i < x:
i += 1
return i*i == x
print(is_perfect_square(15))
# False
print(is_perfect_square(16))
# True
The sum of the first odd integers, beginning with one, is a perfect square.
See proof
1 = 1
1 + 3 = 4
1 + 3 + 5 = 9
1 + 3 + 5 + 7 = 16
and so on .....
So here, we can make use of this important fact to find a solution without using pow() or sqrt() in-built functions.
num = int(input("Enter a positive integer: "))
odd = 1
while num > 0:
num -= odd
odd += 2
if num == 0:
print('It is a pefect square')
else:
print('It is not a pefect square')
I guess it is not a place to answer such questions, but here is a super straightforward solution without using any tricks.
num=int(input("Enter a positive integer: "))
for i in range(num + 1): # in case you enter 1, we need to make sure 1 is also checked
pow = i * i
if pow == num:
print('%d is a pefect square' % num)
break
elif pow > num:
print('%d is not a pefect square' % num)
break
Instead of dividing and taking the remainder, multiply the base and see if it matches the number you are testing. For instance.
for i in range(1, num + 1):
sq = i * i
if sq == num:
print(f"{i} squared is exactly {num}")
break
if sq > num:
print(f"{num} is not a perfect square")
break
You might get a better mark if you do something more clever than increment from 1. A binary search would speed things up a lot for large numbers.
Hey Buddy Try This Code,
num=int(input("Enter a positive integer: "
base=1
while num/base>base:
base=base+1
if (num/base)%1==0:
print(num,"is a square")
else:
print(num,"is not a square")
It should work I tried it
Jai hind jai bharat
Here is something that I came up with:
from math import *
num = eval(input('Enter a number: '))
sq = sqrt(num)
sq1 = sq%1 #here we find the decimal value and then..
if sq1 == 0.0: #if the value = 0 it is a perfect square else it is not, only perfect
squares will be whole numbers.
print(f'{num} is a perfect square')
else:
print(f'{num} is not a perfect square')

Recursive square root loop in python with a epsilon of .0001

I need help with a square root calculator.
The directions are as follows:
"You need to implement the Babylonian Method for computing square roots. Based on that core functionality, you are to write an interactive program that:
Prompts the user to enter an integer value above zero.
Checks to ensure that the value is indeed above zero. If not, the program displays an error message and asks for the input again.
Computes the square root of the value using the Babylonian Method outlined above.
Displays the square root to the user formatted to show exactly 3 decimal places (no more than 3, and no less than 3)."
I can't use the sqrt function. I'm getting really close but can't quite get to the right loop. Here's what I have so far
# Ask user if they would like to calculate a square root for a single number or range.
single = input("Enter 'single' or 'range' to solve for a single square root or a range of values, respectively: ")
# Set error message to let the user know 'range' calculation are not currently available.
if single == 'single' or 'Single':
# Ask user to enter a positive integer.
number = int(input("Enter a positive integer value: "))
# Set error message asking for valid number if user enters something other than a positive integer.
while number < 0:
print("Please enter a valid number.")
else:
# Choose epsilon
epsilon = .0001
# Choose estimate for the square root of x
estimate = 4
# Evaluate the estimate
while number - estimate > epsilon:
# Calculate the square root using the Babylonian Method.
estimate = (number + 1.0) / 2.0
second_estimate = (estimate + number / estimate) / 2.0
# Print the users selected value and its square root.
print("Value", " ", "Square Root")
print(" ", number, " ", format(second_estimate, '.3f'))
else:
# Tell user 'range' calculation are not currently available.
print("That function is not currently available.")
The condition for the while loop is wrong. number is 9 and estimate goes to 3. So you have to check number - estimate*estimate (take the absolute value because estimate converges to 3 from above for a starting value of 4). You dont need the first estimate according to Babylonian method on wikipedia.
Also estimate is always 5 in your code. (estimate = (number + 1.0) / 2.0 where number is always 9)
number = 9
epsilon = .0001
estimate = 4
while abs(number - estimate*estimate) > epsilon:
estimate = (estimate + number/estimate) / 2.0
print("Value", " ", "Square Root")
print(" ", number, " ", format(estimate, '.4f'))
Result:
Value Square Root
9 3.1250
Value Square Root
9 3.0025
Value Square Root
9 3.0000

The second root of a number is up to four digits without decomposing it

I want to calculate the root of a number up to four decimal places without rendering and I use the following code but I can not print out the output without rendering the output.
import math
num = float(input('Enter a number: '))
num_sqrt = math.sqrt(num)
print('The square root of %0.4f is %0.4f'%(num ,num_sqrt))
For example, if the inputs are as follows:
1
2
3
19
The output should be as follows:
1.0000
1.4142
1.7320
4.3588
If you're printing only 4 decimals and you don't want the number rounded that means you want the decimals truncated and regular formatting methods don't provide facilities for that.
You can easily achieve that if you pre-process your number as:
def truncate_number(number, decimals):
factor = 10.0 ** decimals
return int(number * factor) / factor
num = float(input('Enter a number: '))
num_sqrt = num ** 0.5 # or math.sqrt(num) if that's what you prefer.
print("The square root of {:.4f} is {:.4f}".format(num, truncate_number(num_sqrt, 4)))
It essentially just multiplies the number with 10^number_of_decimals, truncates the decimals by converting it to an int and then divides it with the same multiplication factor - this, in effect, leaves only the decimals you're interested in.
You don't even nedd to use formatting directives after pre-processing your number as Python won't print trailing zeros so a simple print("The square root of {} is {}".format(num, truncate_number(num_sqrt, 4))) should suffice.
If you want all answers to have four decimal places, you can use .format as in...
import math
num = float(input('Enter a number: '))
num_sqrt = math.sqrt(num)
print('The square root of {} is {:0.4f}'.format(num, num_sqrt))
notice the {:0.4f} in the print statment
: introduces the format spec
0 enables sign-aware zero-padding for numeric types
.4 sets the precision to 4
f displays the number as a fixed-point number

Categories

Resources