1 Fibonacci
Fibonacci为1200年代的欧洲数学家,在他的著作中曾经提到:若有一只兔子每个月生一只小兔子,一个月后小兔子也开始生产。起初只有一只兔子,一个月后就有两只兔子,两个月后有三只兔子,三个月后有五只兔子(小兔子投入生产)……
这就是Fibonacci数列,一般习惯称之为费式数列,例如:1,1,2,3,5,8,13,21,34,55,89,……
- public class Fibonacci {
- public static void main(String[] args) {
- int[] fib = new int[20];
- fib[0] = 0;
- fib[1] = 1;
- for(int i = 2; i < fib.length; i++)
- fib[i] = fib[i-1] + fib[i-2];
- for(int i = 0; i < fib.length; i++)
- System.out.print(fib[i] + " ");
- System.out.println();
- }
- }
- public class Fibonacci {
- public static void main(String[] args) {
- int[] fib = new int[20];
- fib[0] = 0;
- fib[1] = 1;
- for(int i = 2; i < fib.length; i++)
- fib[i] = fib[i-1] + fib[i-2];
- for(int i = 0; i < fib.length; i++)
- System.out.print(fib[i] + " ");
- System.out.println();
- }
- }
2 巴斯卡(Pascal)
三角形基本上就是在解nCr ,因为三角形上的每一个数字各对应一个nCr ,其中n为row,而r为colnmu
- import java.awt.*;
- import javax.swing.*;
- public class Pascal extends JFrame {
- public Pascal() {
- setBackground(Color.white);
- setTitle("巴斯卡三角形");
- setSize(520, 350);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- show();
- }
- private long combi(int n, int r){
- int i;
- long p = 1;
- for(i = 1; i <= r; i++)
- p = p * (n-i+1) / i;
- return p;
- }
- public void paint(Graphics g) {
- final int N = 12;
- int n, r, t;
- for(n = 0; n <= N; n++) {
- for(r = 0; r <= n; r++)
- g.drawString(" " + combi(n, r),
- (N-n)*20 + r * 40, n * 20 + 50);
- }
- }
- public static void main(String args[]) {
- Pascal frm = new Pascal();
- }
- }
- import java.awt.*;
- import javax.swing.*;
- public class Pascal extends JFrame {
- public Pascal() {
- setBackground(Color.white);
- setTitle("巴斯卡三角形");
- setSize(520, 350);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- show();
- }
- private long combi(int n, int r){
- int i;
- long p = 1;
- for(i = 1; i <= r; i++)
- p = p * (n-i+1) / i;
- return p;
- }
- public void paint(Graphics g) {
- final int N = 12;
- int n, r, t;
- for(n = 0; n <= N; n++) {
- for(r = 0; r <= n; r++)
- g.drawString(" " + combi(n, r),
- (N-n)*20 + r * 40, n * 20 + 50);
- }
- }
- public static void main(String args[]) {
- Pascal frm = new Pascal();
- }
- }