Can any one help me with this one . I was trying to write a prog for finding 'LCM'. I want to equate these variable - python-3.x

Here c and d basically represent tables of respective number for variable a and b...i am trying to match the least common product from these table.Please help me figure it out
a=(input('your first no: '))
b=(input('your second no: '))
for i in range(1,100):
c=a*i
d=b*i
if (c==d):
print('lcm is')

Here is a program that will work. It will also calculate the LCM of more than two numbers.
from collections import Counter
from operator import mul
from functools import reduce
def primeFactors(n):
if not isinstance(n, int) or n < 1:
raise ValueError("must be positive integer")
factors = []
while n % 2 == 0:
factors.append(2)
n /= 2
i = 3
while n != 1:
while n % i == 0:
factors.append(i)
n /= i
i += 2
return factors
def get_lcm(numbers):
factorisations = [Counter(primeFactors(n)) for n in numbers]
primes = frozenset().union(*(set(x.keys()) for x in factorisations))
primes_to_max_powers = (p ** max(*(x.get(p,0) for x in factorisations))
for p in primes)
return reduce(mul, primes_to_max_powers, 1)
a = int(input('your first no: '))
b = int(input('your second no: '))
print('lcm is', get_lcm([a, b]))
Or you can do this instead but it might be a bit slower:
a = input('your first no: ')
b = input('your second no: ')
for i in range(max(a, b), a * b + 1):
if i % a == 0 and i % b == 0:
lcm = i
break
print('lcm is ', lcm)

Use the formula lcm(a,b) = a⋅b / gcd(a,b). Python has a gcd function in the standard library:
from fractions import gcd
def least_common_multiple(a, b):
return a * b / gcd(a, b)
Since Python 3.6, it's arguably preferable to use the gcd builtin from math:
try:
from math import gcd
except ImportError:
from fractions import gcd
def least_common_multiple(a, b):
return a * b / gcd(a, b)

Related

Why is my simple code taking so much time to execute when i give in large numbers as input?

I have written a simple code to print the largest prime factor of a given number from Project Euler. It works just fine for numbers like 24, but there is no response from the python shell for large numbers!
a=600851475143
b=[]
for i in range(2,600851475143):
if a%i==0:
if i==2:
b.append(i)
continue
for j in range(2,i+1):
if j==i:
b.append(i)
if i%j==0:
break
print(max(b))
print(b)
You can use an algorithm like this to get large factors of prime numbers:
import math
def LLL(N):
p = 1<<N.bit_length()-1
if N == 2:
return 2
if N == 3:
return 3
s = 4
M = pow(p, 2) - 1
for x in range (1, 100000):
s = (((s * N ) - 2 )) % M
xx = [math.gcd(s, N)] + [math.gcd(s*p+x,N) for x in range(7)] + [math.gcd(s*p-x,N) for x in range(1,7)]
try:
prime = min(list(filter(lambda x: x not in set([1]),xx)))
except:
prime = 1
if prime == 1:
continue
else:
break
return N/prime

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million

sum_ans=17
for i in range(11,2000000):
for j in range(2,int(i**0.5)):
if i%j==0:
break
else:
sum_ans+=i
print(sum_ans)
The code i have return gives answer 143064094781 and the correct answer is 142913828922 but i can not figure out where i have gone wrong. So can any one help me.
Range's stop parameter is exclusive. This means that your code is only calculating j from 2 to 1 less than i**0.5. To fix this you can add 1, meaning that your end code will look a little like this, providing the correct output of 142913828922:
sum_ans=17
for i in range(11,2000000):
for j in range(2,int(i**0.5+1)):
if i%j==0:
break
else:
sum_ans+=i
print(sum_ans)
What about about this:
def isPrime(x):
prime = True
for i in range(2, x):
if x % i == 0:
prime = False
break
else:
continue
return prime
primes = (a for a in range(2, 2000000) if isPrime(a))
print(sum(primes))
# output
142913828922
This code will take a few minutes to execute. Buckle up!!
def sumPrimes(n):
sum =0
for i in range(2 ,n):
for j in range(2, int(i / 2) +1):
if (i % j) == 0:
break
else:
sum += i
return sum
print(sumPrimes(2000000))
If you iterating over all numbers below 2 million, you might as well sieve them using the Sieve of Eratoshenes:
from math import ceil, sqrt
def sieve(n):
nums = list(range(2,n+1))
primes = []
p = 2
k = 1+ ceil(sqrt(n))
while p < k:
primes.append(p)
nums = [num for num in nums[1:] if num % p > 0]
p = nums[0]
return primes + nums
Then sum(sieve(2000000)) evaluates to 142913828922. It takes about 5 seconds to run on my machine.

How can i sum co-prime numbers in a pair

I have this list
a = [1,2,3,4,5,6,7,8,9]
I want to find out that how many co-prime pair elements of the list add up to sum=9
Ex, (1+8) = 9 , (2+7) = 9 , (3+6)=9 , (4+5)=9, (5+4)=9 , (6+3)=9, (7+2)=9 , (8+1)=9
Note that i don't want (3+6) as they are prime numbers. And i also don't want (7+2)=9 as it has already occurred (means 2,7 has been already taken in account)
I tried this But it takes repeated values too.
a = [1,2,3,4,5,6,7,8,9]
count=0
for m in a:
for n in a:
total=m+n
if(total==9):
s=str(m) + '+'+ str(n) + "="
print(s , m+n)
count=count+1
print("Count =" ,count)
The result should have count=3
Your mistake is in the way of doing the loops, so you repeat values.
Try this:
#from math import gcd as bltin_gcd
a = [1,2,3,4,5,6,7,8,9]
count = 0
def __gcd(a, b):
# Everything divides 0
if (a == 0 or b == 0): return 0
# base case
if (a == b): return a
# a is greater
if (a > b):
return __gcd(a - b, b)
return __gcd(a, b - a)
# Only python 3
# def coprime(a, b):
# return bltin_gcd(a, b) == 1
for i in range(0,9):
for j in range(i+1,9):
if __gcd(a[i], a[j]) == 1 and a[i] + a[j] == 9:
count += 1
print str(a[i]) + ' ' + str(a[j])
print 'Count = ' + str(count)
In number theory, two integers a and b are said to be relatively prime, mutually prime, or coprime if the only positive integer that divides both of them is 1. Consequently, any prime number that divides one does not divide the other. This is equivalent to their greatest common divisor being 1.
for m in a:
for n in a:
You are not selecting pairs by using this loops, ie. you are picking the first element in both the outer and inner loop during your first iteration.
if(total==9):
You are not checking the condition if the selected pair of numbers are coprime. You are only verifying the sum.
A pythonic solution may be obtained with a one-liner:
from math import gcd
a = [1,2,3,4,5,6,7,8,9]
pairs = [(m,n) for m in a for n in a if n > m and m+n == 9 and gcd(m,n) == 1]
Result :
pairs --> [(1, 8), (2, 7), (4, 5)]
If you are sure to never, never need the pairs but only the number of pairs (as written in the OP), the most efficient solution may be:
count = len([1 for m in a for n in a if n > m and m+n == 9 and gcd(m,n) == 1])
EDIT : I inversed the three conditions in the if statement for improved benefit from lazy boolean evaluation
You can solve this if you have something that calculates your prime factorization in python:
from functools import lru_cache
# cached function results for pime factorization of identical nr
#lru_cache(maxsize=100)
def factors(nr):
# adapted from https://stackoverflow.com/a/43129243/7505395
i = 2
factors = []
while i <= nr:
if (nr % i) == 0:
factors.append(i)
nr = nr / i
else:
i = i + 1
return factors
start_at = 1
end_at = 9
total = 9
r = range(start_at, end_at+1)
# create the tuples we look for, smaller number first - set so no duplicates
tupls = set( (a,b) if a<b else (b,a) for a in r for b in r if a+b == total)
for n in tupls:
a,b = n
f_a = set(factors(a))
f_b = set(factors(b))
# if either set contains the same value, the f_a & f_b will be truthy
# so not coprime - hence skip it
if f_a & f_b:
continue
print(n)
Output:
(2, 7)
(1, 8)
(4, 5)

Using Recursive Functions in Python to find Factors of a Given Number

Have tried searching for this, but can't find exactly what I'm looking for.
I want to make a function that will recursively find the factors of a number; for example, the factors of 12 are 1, 2, 3, 4, 6 & 12.
I can write this fairly simply using a for loop with an if statement:
#a function to find the factors of a given number
def print_factors(x):
print ("The factors of %s are:" % number)
for i in range(1, x + 1):
if number % i == 0: #if the number divided by i is zero, then i is a factor of that number
print (i)
number = int(input("Enter a number: "))
print (print_factors(number))
However, when I try to change it to a recursive function, I am getting just a loop of the "The factors of x are:" statement. This is what I currently have:
#uses recursive function to print all the letters of an integer
def print_factors(x): #function to print factors of the number with the argument n
print ("The factors of %s are:" % number)
while print_factors(x) != 0: #to break the recursion loop
for i in range(1,x + 1):
if x % i == 0:
print (i)
number = int(input("Enter a number: "))
print_factors(number)
The error must be coming in either when I am calling the function again, or to do with the while loop (as far as I understand, you need a while loop in a recursive function, in order to break it?)
There are quite many problems with your recursive approach. In fact its not recursive at all.
1) Your function doesn't return anything but your while loop has a comparision while print_factors(x) != 0:
2) Even if your function was returning a value, it would never get to the point of evaluating it and comparing due to the way you have coded.
You are constantly calling your function with the same parameter over and over which is why you are getting a loop of print statements.
In a recursive approach, you define a problem in terms of a simpler version of itself.
And you need a base case to break out of recursive function, not a while loop.
Here is a very naive recursive approach.
def factors(x,i):
if i==0:
return
if x%i == 0:
print(i)
return factors (x,i-1) #simpler version of the problem
factors(12,12)
I think we do using below method:
def findfactor(n):
factorizeDict
def factorize(acc, x):
if(n%x == 0 and n/x >= x):
if(n/x > x):
acc += [x, n//x]
return factorize(acc, x+1)
else:
acc += [x]
return acc
elif(n%x != 0):
return factorize(acc, x+1)
else:
return acc
return factorize(list(), 1)
def factors(x,i=None) :
if i is None :
print('the factors of %s are : ' %x)
print(x,end=' ')
i = int(x/2)
if i == 0 :
return
if x % i == 0 :
print(i,end=' ')
return factors(x,i-1)
num1 = int(input('enter number : '))
print(factors(num1))
Recursion is a functional heritage and so using it with functional style yields the best results. This means avoiding things like mutations, variable reassignments, and other side effects. That said, here's how I'd write factors -
def factors(n, m = 2):
if m >= n:
return
if n % m == 0:
yield m
yield from factors(n, m + 1)
print(list(factors(10))) # [2,5]
print(list(factors(24))) # [2,3,4,6,8,12]
print(list(factors(99))) # [3,9,11,33]
And here's prime_factors -
def prime_factors(n, m = 2):
if m > n:
return
elif n % m == 0:
yield m
yield from prime_factors(n // m, m)
else:
yield from prime_factors(n, m + 1)
print(list(prime_factors(10))) # [2,5]
print(list(prime_factors(24))) # [2,2,2,3]
print(list(prime_factors(99))) # [3,3,11]
def fact (n , a = 2):
if n <= a :
return n
elif n % a != 0 :
return fact(n , a + 1 )
elif n % a == 0:
return str(a) + f" * {str(fact(n / a , a ))}"
Here is another way. The 'x' is the number you want to find the factors of. The 'c = 1' is used as a counter, using it we'll divide your number by 1, then by 2, all the way up to and including your nubmer, and if the modular returns a 0, then we know that number is a factor, so we print it out.
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)

Logic to find out the prime factors of a number

I have created the below script to find out the prime factors of a number :
def check_if_no_is_prime(n):
if n <= 3:
return True
else:
limit = int(math.sqrt(n))
for i in range(2,limit + 1):
if n % i == 0:
return False
return True
def find_prime_factors(x):
prime_factors = []
if check_if_no_is_prime(x):
prime_factors.append(1)
prime_factors.append(x)
else:
while x % 2 == 0 and x > 1:
prime_factors.append(2)
x = x // 2
for i in range(3,x+1,2):
while x % i == 0 and x > 1:
if check_if_no_is_prime(i):
prime_factors.append(i)
x = x // i
if x <= 1:
return prime_factors
return prime_factors
no = int(input())
check = find_prime_factors(no)
print (check)
I am not sure whether this is the best and efficient way to do this ?
Can someone please point out any better way to do this ?
using sieve of erathnostanes to get all prime numbers from 2 to whatever limit inputted
def sieve(N):
from math import floor,sqrt
A=[1 for x in range(N+1)]
for count in range(2):
A[count]=0
for i in range(floor(sqrt(N))+1):
if A[i]==1:
for k in range(i*i,N+1,i):
A[k]=0
ans=list(enumerate(A))
res=[]
for (i,j) in ans:
if j==1:
res+=[i]
return res
print(sieve(100))
#my code

Resources