简体   繁体   中英

Divide by zero, can't find the problem in this program which runs Euclid's algorithm to find the greatest common divisor

public static long[] simp (long [] a) {
    long c = a[0];
    long d = a[1];
    if ( a[0]<0 ) {
        a[0] = -1*a[0];
    }
    if (a[1]>a[0]) {
        long v = a[0];
        a[0]=a[1];
        a[1]=v;
    }
    while (a[1] > 0) {
        long t = a[0];
        a[0] = a[1];
        a[1] = t%a[1];
        System.out.println(a[0]+"/"+a[1]);
    }
    a[0] = c/a[0];
    a[1] = d/a[0];
    System.out.println(a[0]+"/"+a[1]);
    return a;
}

I followed the steps of Euclid's algorithm but I was stunned when a divide by zero problem appeared. I don't know how it can happen.

The problem is with the below two lines.

a[0] = c/a[0];
a[1] = d/a[0];

First statement will make a[0] as 0 since c is 0. Next statement will be 1/0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM