Posted on 2010-05-22 13:40
java小爬虫 阅读(3331)
评论(2) 编辑 收藏
今天参加了一场java笔试,考了斐波那契
数列。以前也见过考阶乘的。今天顺手把它写下来。
public class Recursion {
public static long factorial(int i) {
if (i < 0)
return -1;
else if (i == 0 || i == 1)
return 1;
else
return i * factorial(i - 1);
}
public static int sum(int i) {
if (i == 0)
return 0;
else
return i + sum(i - 1);
}
public static int fibonacci(int i) {
if (i == 0 || i == 1)
return 1;
else
return fibonacci(i - 1) + fibonacci(i - 2);
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i + "!= " + factorial(i));
System.out.println("sum(" + i + "!) = " + sum(i));
System.out.println("fibonacci(" + i + ")= " + fibonacci(i));
System.out.println("=========================");
}
}
}