Java 作业题1
1. 斐波那契
package Test; import java.util.Scanner; //import java.util.*; public class Main { public static int f(int a) { if(a<0) return -1; if(a == 0) { return 0; } if(a== 1 || a== 2) return 1; else return f(a-1)+f(a-2); } public static void main(String[] args) { Scanner inp = new Scanner(System.in); int n = inp.nextInt(); System.out.println( f(n)); } }
2. 闭区间随机数
package Test; import java.util.Scanner; //import java.util.*; public class Main { public static void main(String[] args) { Scanner inp = new Scanner(System.in); int a = inp.nextInt(); int b = inp.nextInt(); int temp=a+(int)(Math.random()*(b+1-a)); System.out.println(temp); } }
3.二项分布
概率公式:
P(ξ=K)= C(n,k) * p^k * (1-p)^(n-k)
C(n, k) = (n-k) !/(k! * (n-k)!),记作ξ~B(n,p),期望:Eξ=np,方差:Dξ=npq,其中q=1-p
根据递推式:C(n,k)=C(n-1,k)+C(n-1,k-1) 可写出递归形式
package Test; import java.util.Scanner; //import java.util.*; public class Main { static int Cot = 0; public static double binomial(int N, int k, double p) { Cot++; if (N == 0 && k == 0) { return 1.0; } if (N < 0 || k < 0) { return 0.0; } return (1.0 - p) * binomial(N - 1, k, p) + p * binomial(N - 1, k - 1, p); } public static void main(String[] args) { //Scanner inp = new Scanner(System.in); System.out.println(binomial(30,15,0.25)+ "\t"+ Cot); //System.out.println(temp); } }
好兄弟 Cot 已经爆了 这个是用来记录调用次数的
n 才30吧 就不行了...
回溯剪枝:
package Test; import java.util.Scanner; //import java.util.*; public class Main { static long Cot = 0; private static double[][] M; private static double binomial(int N, int k, double p) { Cot++; if (N == 0 && k == 0) { return 1.0; } if (N < 0 || k < 0) { return 0.0; } if (M[N][k] == -1) { M[N][k] = (1.0 - p) * binomial(N - 1, k, p) + p * binomial(N - 1, k - 1, p); } return M[N][k]; } public static double Binomial(int N, int k, double p) { M = new double[N + 1][k + 1]; for (int i = 0; i <= N; i++) { for (int j = 0; j <= k; j++) { M[i][j] = -1; } } return binomial(N, k, p); } public static void main(String[] args) { System.out.println(Binomial(20,5,0.1)+ "\t"+ Cot); } }
行!
非递归 (这个才是真的快)
package Test; import java.util.Scanner; //import java.util.*; public class Main { //计算组合数 public static double combination(double N, double k) { double min = k; double max = N-k; double t; double NN=1; double kk=1; if(min>max){ t=min; min = max; max=t; } while(N>max){//分母中较大的那部分阶乘约分不用计算 NN=NN*N; N--; } while(min>0){//计算较小那部分的阶乘 kk=kk*min; min--; } return NN/kk; } //计算二项分布值 public static double binomial(int N,int k,double p) { double a=1; double b=1; double c =combination(N,k); while((N-k)>0){ //计算(1-p)的(N-k)次方 a=a*(1-p); N--; } while(k>0){ //计算p的k次方 b=b*p; k--; } return c*a*b; } public static void main(String[] args) { System.out.println(binomial(20,5,0.1)); } }