1.纯随机数发生器
public class suijishu { private static final int N = 200; private static final int LEFT = 40; private static final int RIGHT = 1000; private static long x0 = 1L; private long a = 1103515245L; private long c = 12345L; private long m = 2147483648L; private long rand ( long r ) { r = ( r * a + c ) % m; return r; } private long little ( int a, int b, long rand ) { return a + rand % ( b - a + 1 ); } private void recursion ( int count, long rand ) { if (count >= N) {return;} rand = rand (rand); long r = little (LEFT, RIGHT, rand); System.out.println (r); recursion (++count, rand); } public static void main ( String[] args ) { suijishu recur = new suijishu (); recur.recursion (0, x0); } }
2.当函数的形参类型不同时,函数可以重载。
3.组合数计算
import java.util.Scanner; public class zuheshu1 { public static int jiecheng(int x){ int m=1; if(x<0) { System.out.println("输入错误"); System.exit(0); } else if(x==0||x==1) m=1; else m=jiecheng(x-1)*x; return m; } public static int jszhs1(int k,int n){ int c=jiecheng(n)/(jiecheng(k)*jiecheng(n-k)); return c; } public static int jszhs2(int n,int k) { int i=1; int c=1; for(i=k;k<n;i++) { c=c*(i/(i+k))*jszhs1(k,i-1); } return c; } public static int jszhs3(int k,int n) { int c=1; if(k==n) {return c;} else {return (n/(n-k))*jszhs3(k,n-1);} } public static void main(String args[]) { System.out.print("请选择组合数运算方法:1组合数公式;2递推杨辉三角;3递归"); Scanner sc=new Scanner(System.in); int d=sc.nextInt(); System.out.print("请输入组合数中的k和n:"); int a=sc.nextInt(); int b=sc.nextInt(); switch(d) { case 1:System.out.println("结果为:"+jszhs1(a,b));break; case 2:System.out.println("结果为:"+jszhs2(a,b));break; case 3:System.out.println("结果为:"+jszhs3(a,b));break; } } }
4.汉诺塔问题
import java.util.Scanner; public class hannuota { public static void yidong(int panzi,int kaishi,int zhongjian,int zuihou) { if(panzi==1) { System.out.println(kaishi+"-->"+zhongjian); return; } yidong(panzi-1,kaishi,zuihou,zhongjian); System.out.println(kaishi+"-->"+zhongjian); yidong(panzi-1,zuihou,zhongjian,kaishi); } public static void main(String args[]) { System.out.println("请输入盘子数:"); Scanner sc=new Scanner(System.in); int n=sc.nextInt(); System.out.println("移动方法为:"); yidong(n,1,3,2); } }
5.回文字符串
import java.util.Scanner; class huiwen { public static int panduan(String s) { int length=s.length(); if(length==0||length==1) return 1; char first=s.charAt(0); char last=s.charAt(length-1); if(first!=last) return 0; return panduan(s.substring(1, length-1)); } public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("请输入一个字符串:"); String s=sc.nextLine(); if(panduan(s)==1) System.out.println("是回文字符串"); else System.out.println("不是回文字符串"); } }