斐波那契数列的递归实现:
public int fn(int n) {
if (n == 1 || n == 2)
return 1;
return fn(n-1)+fn(n-2);
}
非递归写法:
public int fn(int n) {
int a =1;
int b = 1;
int tmp;
if (n == 1 || n == 2)
return 1;
for (int i = 2; i < n; i++) {
tmp = a +b;
a = b;
b = tmp;
}
return b;
}
约瑟夫环找到一种简单的方法:
public class JosephRing {
public JosephRing(){};
public void cac(int m, int n) {
List<Integer> ls = new ArrayList<Integer>();
for (int i = 1; i <= n; i++)
ls.add(i);
int count = 0;
for (int i = 1; i <= n; i++) {
count = (--count + m) % ls.size();
System.out.print(ls.remove(count) + " ");
}
}
public static void main(String[] args) {
new JosephRing().cac(7, 5);
}
}
时间: 2024-10-29 11:31:25