Highest Common Factor on Python
HCF on Python
Hello Programmer's
Welcome to my blog again..
Here i show you how to calculate "Highest Common Factor between Two numbers" on Python
Welcome to my blog again..
Here i show you how to calculate "Highest Common Factor between Two numbers" on Python
It interesting because when we attend an interview or exam, the question come,
but we struggle to calculate the value if two numbers are big..
Here Problem is solve, You won't crush your brain...
Simple code work for us...
but we struggle to calculate the value if two numbers are big..
Here Problem is solve, You won't crush your brain...
Simple code work for us...
Okay..Let's see..
CODE : (Two Numbers)
# find hcf for two numbers
from collections import Counter
a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
sum,a_f,b_f,sum1 = a,[],[],b
while True:
for i in range(2,a+1):
if sum % i == 0:
sum = sum // i
a_f.append(i)
break
if sum == 1:
break
while True:
for i in range(2,b+1):
if sum1 % i == 0:
sum1 = sum1 // i
b_f.append(i)
break
if sum1 == 1:
break
print(a_f,b_f)
c1 = Counter(a_f)
c2 = Counter(b_f)
d = list((c1 & c2).elements())
total =1
for i in d:
total *= i
print(f'Highest common factor: {total}')
------
BONUS CODE:
# find hcf for three numbers
from collections import Counter
a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
c = int(input('Enter third number: '))
sum,a_f,b_f,c_f,sum1,sum2 = a,[],[],[],b,c
while True:
for i in range(2,a+1):
if sum % i == 0:
sum = sum // i
a_f.append(i)
break
if sum == 1:
break
while True:
for i in range(2,b+1):
if sum1 % i == 0:
sum1 = sum1 // i
b_f.append(i)
break
if sum1 == 1:
break
while True:
for i in range(2,c+1):
if sum2 % i == 0:
sum2 = sum2 // i
c_f.append(i)
break
if sum2 == 1:
break
print(a_f,b_f,c_f)
c1 = Counter(a_f)
c2 = Counter(b_f)
c3 = Counter(c_f)
d = list((c1 & c2 & c3).elements())
total =1
for i in d:
total *= i
print(f'Highest common factor: {total}')
------
By
PyKAR
PyKAR
Comments
Post a Comment