日期:2014-05-20 浏览次数:20809 次
public class Recursion { /* * 用递归判断一个数是不是质数? */ static int numberO; static boolean flag = true; public static void main(String[] args) { if (isPrimeNumber(-1) > 0) System.out.println(numberO + " 是质数"); else System.out.println(numberO + " 是非质数"); } private static int isPrimeNumber(int number) { if (flag) { number = numberO = Math.abs(number); flag = false; if (numberO < 2) return -1; } if (number > 2 && (numberO % (--number)) == 0) return -1; else return number > 2 ? isPrimeNumber(number) : 1; } }
------解决方案--------------------
更加完善的递归调用了
public class Recursion { /* * 用递归判断一个数是不是质数? */ static int numberO; static boolean flag = true; public static void main(String[] args) { for (int i = 0; i < 100; i++) { if (isPrimeNumber(i) > 0) System.out.println(numberO + " 是质数"); else System.out.println(numberO + " 是非质数"); flag = true; } } private static int isPrimeNumber(int number) { if (flag) { number = numberO = Math.abs(number); flag = false; if (numberO < 2) return -1; } if (number > 2 && (numberO % (--number)) == 0) return -1; else return number > 2 ? isPrimeNumber(number) : 1; } }