To find the lcm of two numbers [duplicate] - python

This question already has answers here:
Division in Python 3 gives different result than in Python 2
(3 answers)
Closed 6 years ago.
I was given the task to compute lcm of any two numbers.I have coded in python.The problem is when i compiled it under python2.7, i got a result which is different from , when i compiled under python3.
import sys
def gcd(a,b):
if b == 0:
return a
remainder = a % b
return gcd(b,remainder)
def lcm(a, b):
return int( (a*b) / gcd(a,b))
if __name__ == '__main__':
input = sys.stdin.read()
a, b = map(int, input.split())
print(int(lcm(a, b)))
Input
226553150 1023473145
Output
46374212988031352 (under python3.5)
46374212988031350 (under python2.7)
Can someone help me ?

In Python 2 the division operator / will perform integer division, and not float division, when dealing with two integers. You can force the Python 3 behavior in Python 2 by importing division from __future__
>>> from __future__ import division
>>> 2/3
1.5

Related

How to take the 5th power python [duplicate]

This question already has answers here:
What does the ** maths operator do in Python?
(5 answers)
Closed 1 year ago.
I want to find the 5th power of a number given by the user. Can i do this without typing:
ans = n * n * n * n * n
and can it be used for higher powers?
Use the ** operator for exponents:
print(5**12)
>>> 224832
We can use this more generally using variables.
exponent = 5
n = 12
ans = n ** exponent
print(ans)
>>> 248832
Other Methods
Since the ** operator caps at an exponent of 256, we can use the built-in pow() function for larger exponents. However, these numbers can be very large.
power = pow(base, exponent)
The math and numpy libraries also can do this using the math.pow() and numpy.power() functions.
An alternative to the ** operator is to use the math library functions.
import math
math.pow(x, y)
Note that this returns a floating point value, while the ** operator will return an int or float based on the type of x.

Replace 5 with 6 in python

I found a program of changing digit 5 with 6 in python , but the issue is I've got it in python2 and if I change it in python3 and rerun it it gives weird output.
The source of python 2 code is
http://www.geeksforgeeks.org/replace-0-5-input-integer/
and my full python3 code is
def convert5to6rec(num):
# Base case for recurssion termination
if(num == 0):
return 0
# Extract the last digit and change it if needed
digit = num % 10
if(digit == 5):
digit = 6
# Convert remaining digits and append the last digit
return convert5to6rec(num/10) * 10 + digit
# It handles 0 to 5 calls convert0to5rec() for other numbers
def convert5to6(num):
if(num == 5):
return 6
else:
return convert5to6rec(num)
# Driver Program
num = 520
print(convert5to6(num))
The output it gives is
170642.43254304124
SO can anyone point out that silly mistake that I left
PS: I need the program to replace the digits 5 with 6.
the expected output should be 620
Change num/10 to num//10. In Python 3, integer division with the / operator produces a floating point result. To get integer division, you need to use the // operator.
Instead of doing it mathematically, you could convert the integer to a string, replace the 5's with 6's and cast it back to an integer. The easiest way to do this would be
int(str(num).replace('5', '6'))
The reason it's not working in python 3 is because of the difference in the behavior of division in python 2 and 3. In python 2, / does a floor division, whereas in python 3, it is a true division.
So in python 2,
In [1]: 11 / 2
Out[1]: 5
In python 3,
In [2]: 11/2
Out[2]: 5.5
For doing floor division in python 3 you will need to use // instead of /. So, you just need to replace / with // in your code.

Computing PI in Python 2, how to stop answer truncating [duplicate]

This question already has answers here:
How to define a decimal class holding 1000 digits in python?
(4 answers)
Closed 7 years ago.
please go easy on me, I've been learning Python about a week!
I thought I'd try calculating Pi using the Rumanujan formula. I am confident I was able to code that correctly.
My answer is truncating and I'd like it to be represented with 200 dp. In C I'd use malloc to do this perhaps but I understand that Python doesn't work that way.
The learning point I'd like to take away from this is: Is the truncation caused by the limit of representing a float, and if so is it possible to fix?
Thanks.
import math
from decimal import *
getcontext().prec = 200
def iterate(n):
sum = 0
Decimal(sum)
sum = (math.factorial(4*n))
sum = (sum/math.pow(math.factorial(n), 4))
sum = sum*((26390*n +1103)/math.pow(396, (4*n)))
return sum
ans=0
Decimal(ans)
print "Choose the number of iterations:\n"
itnum = int(raw_input())
for n in range (0, itnum+1):
this_iteration = 0
Decimal(this_iteration)
this_iteration = iterate(n)
ans = ans + this_iteration
ans = ans*(math.pow(8, 0.5)/9801)
ans = 1/ans
print "%.200f" % ans
Your snippet
sum = 0
Decimal(sum)
leaves sum set to the int 0, and computes and throws away a Decimal equivalent. Use, instead, an assignment statement:
sum = Decimal(0)
Next, you'll need to ensure every intermediate result is also converted appropriately to Decimal (and floats by default are not).
Personally, I'd recommend using gmpy2 instead, but then, I'm biased:-).

Where can I convert x to float in this Python function? [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 8 years ago.
How can I make this function return and print a float:
x = input ("Enter 5 numbers:")
def average(x):
return sum(x) / len(x)
print average(x)
In python 2.x, int object divided by int yields int.
You should convert one (or both) of the operand to float to get float result:
>>> 10 / 2
5
>>> float(10) / 2
5.0
Or turn on true division using __future__ module:
>>> from __future__ import division
>>> 10 / 2
5.0

Python3.3 rounding up

In Python I would like to divide two numbers and if the answer is not an integer I want the number to be rounded up to the number above.
For example 100/30 not to give 33.3 but to give 4.
Can anyone suggest how to do this? Thanks.
You can use the math.ceil() function:
>>> import math
>>> math.ceil(100/33)
4
you can use the ceil function in math library that python has, but also you can take a look why in a logical sense
a = int(100/3) # this will round down to 3
b = 100/3 # b = 33.333333333333336, a and b are not equal
so we can generalize into the following
def ceil(a, b):
if (b == 0):
raise Exception("Division By Zero Error!!") # throw an division by zero error
if int(a/b) != a/b:
return int(a/b) + 1
return int(a/b)

Categories

Resources