Simple greatest common factor script

Discussion in 'Python' started by fejky, Nov 29, 2009.

  1. fejky

    fejky Guest

    Simple script that calculates greatest common factor using euclid's
    theorem.

    a = int(input("Enter a: "))
    b = int(input("Enter b: "))
    m = 1

    while True:
    if m != 0:
    if b > a:
    n = b/a
    m = b % a
    print b, " : ", a, " = ", n, " i ost ", m
    b = m
    if a > b:
    n = a/b # line 13
    m = a % b
    print a, " : ", b, " = ", n, " i ost ", m
    a = m
    if a == b:
    print "NZM(", a, ",", b, ") = ", a
    m = 0
    else: break

    but when i run this script:
    Enter a: 12345
    Enter b: 54321
    54321 : 12345 = 4 i ost 4941
    12345 : 4941 = 2 i ost 2463
    4941 : 2463 = 2 i ost 15
    2463 : 15 = 164 i ost 3
    15 : 3 = 5 i ost 0
    Traceback (most recent call last):
    File "D:\Programing\Python_2.6\math\NZM.py", line 13, in <module>
    n = a/b
    ZeroDivisionError: integer division or modulo by zero

    I don't see how this script is able to divide by zero. If a and b
    switch places everything works ok.

    Thanks
     
    fejky, Nov 29, 2009
    #1
    1. Advertising

  2. > I don't see how this script is able to divide by zero. If a and b
    > switch places everything works ok.


    Have a look at your if-statements. It is possible, that both your if's
    are executed in one loop iteration (you can check this using pdb). You
    may want to try elif instead.

    - Patrick
     
    Patrick Sabin, Nov 29, 2009
    #2
    1. Advertising

  3. fejky

    fejky Guest

    I have no idea how i missed that.

    Thanks!
     
    fejky, Nov 29, 2009
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Kian Goh
    Replies:
    2
    Views:
    406
    Steve C. Orr, MCSD
    Jul 24, 2003
  2. Frederick Gotham

    Highest Common Factor

    Frederick Gotham, Oct 23, 2006, in forum: C Programming
    Replies:
    10
    Views:
    885
    Elijah Cardon
    Oct 25, 2006
  3. Replies:
    4
    Views:
    1,331
    Martin Ambuhl
    May 30, 2007
  4. Replies:
    0
    Views:
    497
  5. Replies:
    2
    Views:
    762
    Gianni Mariani
    May 30, 2007
Loading...

Share This Page