some problem with Greatest Common Divisor (Python)

Back to General discussions forum

vasmitr95     2015-07-28 20:20:46

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()
vasmitr95     2015-07-28 20:30:29
// there was duplicate message, I removed it - Admin
Rodion (admin)     2015-07-28 21:15:15
User avatar

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?

vasmitr95     2015-07-29 07:02:28

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)
Rodion (admin)     2015-07-29 07:36:11
User avatar

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?

vasmitr95     2015-07-29 10:58:31

Yes, it works. Thanks for help.

Please login and solve 5 problems to be able to post at forum