Back to General discussions forum
Hello there. My program prints some correct results and some wrong together (but with data from example it works normal). Help pls. code:
def gcd_and_lcm():
fin = open('data.txt')
for i, line in enumerate(fin):
if i > 0:
numbs = list(map(int, line.split(' ')))
a = max(numbs)
b = min(numbs)
c = a
while a > b:
a = a - b
lcm = c * b / a
result = '(' + str(int(a)) + ' ' + str(int(lcm)) + ')'
print(result, ' ', end="")
fin.close
gcd_and_lcm()
// there was duplicate message, I removed it - Admin
Hi!
If the second post is a duplicate - would you allow me to cut it out?
As about your question - could you please provide example of correct and incorrect answer so that we can investigate the matter together?
Yes, you can cut it out. I'm sorry.
this is my answer:
(720 4320) (1594 31066) (1050 31500) (234 72540) (293 1869) (1275 15900) (16 14630) (2117 14589) (924 3696) (1953 5771) (869 3748) (50 83537) (2 5684) (11 10205) (572 5530) (352 10205) (27 4925) (2 4) (693 8061) (650 7800) (5 19970)
and this is correct:
(720 4320) (1 49519515) (1050 31500) (234 72540) (1 547808) (85 238510) (4 58520) (73 423108) (924 3696) (63 178920) (79 41238) (1 4176855) (2 5684) (1 112260) (52 60840) (1 3592330) (1 132983) (2 4) (99 56430) (650 7800) (5 19970)
Thank you for this information! I think I get it now. Probably the algorithm was not explained well enough and you did not understand it correctly, I'm sorry.
See, you really should subtract one value from another, but you should only stop when one of the numbers come
to 0
- not when a
becomes less than b
.
For example, we have 10
and 4
. We subtract 4
twice from 10
and then we have 2
and 4
. Here we should
proceed subtracting smaller from larger - we subtract 2
from 4
twice, and then we have 2
and 0
. That
means that 2
is GCD.
Does it help?
Yes, it works. Thanks for help.