All pastes #174970 Raw Edit

Fibonacci Rabbits

public java v1 · immutable
·published 2006-09-18 11:36 UTC
rendered paste body
import java.io.*;class DamnRabbits {	static int d;	static int gb[];	static int ngb[];	static int born[];	public static void main(String[] args) {		while(true) {			try {			main();			} catch ( IOException e ) {			}		}	}	public static void main() throws IOException {		BufferedReader r = new BufferedReader( new InputStreamReader(System.in));		System.out.print("Number of months? ");		int n = Integer.parseInt( r.readLine() );		System.out.print("How long each pair of rabbits live? ");		d = Integer.parseInt( r.readLine() );		//keep track		gb = new int[n + 1];		ngb = new int[n + 1];		born = new int[n + 1];		for (int i = 0; i < n + 1; i++ ) {			gb[i] = -1;			ngb[i] = -1;			born[i] = -1;		}		//first month		gb[1] = 0;		ngb[1] = 0;		born[1] = 1;		System.out.println("There will be " + total(n) + " pairs after " + n + " months.\n\n");	}	static int total(int n) {		return gb(n) + ngb(n) + born(n);	}	static int gb(int n) {		if ( n > 0 ) {			if ( gb[n] > -1 ) {				return gb[n];			} else {				int toberet = total(n - 1) - born(n - d) - born(n - 1);				gb[n] = toberet;				return toberet;			}		}		return 0;	}	static int ngb(int n) {		if ( n > 0 ) {			if ( ngb[n] > -1 ) {				return ngb[n];			} else {				int toberet = born(n - 1);				ngb[n] = toberet;				return toberet;			}		}		return 0;	}	static int born(int n) {		if ( n > 0 ) {			if ( born[n] > -1 ) {				return born[n];			} else {				int toberet = gb[n];				born[n] = toberet;				return toberet;			}		}		return 0;	}}