来自SPOJ的问题AE2B中的非零退出代码

时间:2011-07-20 13:44:50

标签: java

我写了一段代码来解决这个问题。

我一直在获得NZEC(非零退出代码运行时错误),但我无法找到代码的哪一部分可能导致任何异常,因为它 只涉及简单的算术运算(不应该被零除以)。

代码的逻辑并不重要,我只是想知道异常可能隐藏在哪里。

任何人都可以发现任何错误吗?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * SPOJ Problem Set (classical) 4302. (K,N)-Knight Problem code: AE2B
 * 
 * @author Eric
 * 
 */
public class AE2B {

    /**
     * @param args
     */
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
        int count = Integer.parseInt(reader.readLine());
        for (int i = 0; i < count; ++i) {
            String[] tokens = reader.readLine().split(" ");
            int k = Integer.parseInt(tokens[0]);
            int n = Integer.parseInt(tokens[1]);
            int x1 = Integer.parseInt(tokens[2]);
            int y1 = Integer.parseInt(tokens[3]);
            int x2 = Integer.parseInt(tokens[4]);
            int y2 = Integer.parseInt(tokens[5]);

            int g = gcd(k, n);
            int dx = Math.abs(x1 - x2);
            int dy = Math.abs(y1 - y2);
            if (g > 1) {
                if ((dx % g != 0) || (dy % g != 0)) {
                    System.out.println("NIE");
                    continue;
                }
                k /= g;
                n /= g;
                dx /= g;
                dy /= g;
            }
            if (k % 2 == 0 || n % 2 == 0) {
                System.out.println("TAK");
            } else if (dx % 2 + dy % 2 == 1) {
                System.out.println("NIE");
            } else {
                System.out.println("TAK");
            }
        }

    }

    static int gcd(int a, int b) {
        if (a < b) {
            return gcd(b, a);
        }
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

}

1 个答案:

答案 0 :(得分:0)

使用你的gcd()方法,我得到了一个堆栈溢出错误:

gcd(-12, -17);

我建议您避免计算负数的GCD:

static int gcd(int a, int b) {
    a = Math.abs(a);
    b = Math.abs(b);
    if (a < b) {
        return gcd(b, a);
    }
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}
相关问题