兔子繁衍和最大公约数(Java版)
一、前言
算法上机作业,本来用C语言写,但VScode一直抽风,最近学校在上Java,不妨换种语法写 目前感受:JavaSE的语法其实和C没啥区别,换汤不换药
二、兔子繁衍问题
1、问题 典型的斐波那契数列
1 、 1 、2 、 3 、 5 、8 、 13 、 21 、34…
2、解决 ① 方法一
迭代关系式 y[ i ] = y[ i-1 ] + y[ i-2 ]
public class Rabit_1 { public static void main(String[] args) { int[] arr=new int[3]; int i,j; System.out.println("请输入当前的月数"); Scanner scanner=new Scanner(System.in); j=scanner.nextInt(); arr[0]=arr[1]=1; //1,2月兔子个数为1 System.out.println("arr[1] = "+arr[0]); System.out.println("arr[2] = "+arr[1]); for(i=2;i<j;i++){ arr[2]=arr[1]+arr[0]; System.out.println("arr["+(i+1)+"] = "+arr[2]); arr[0]=arr[1]; arr[1]=arr[2]; } } }
② 方法二
迭代关系式 a = b+c; b = a+c; c = a+b;
public class Rabit2 { public static void main(String[] args) { int a=1,b=1,c,i; for(i=1;i<=4;i++){ c=a+b; a=b+c; b=c+a; //输出的结果不完美 System.out.print(a+" "+b+" "+c+" "); } } }
③ 方法三
迭代关系式 a = a+b; b = a+b;
public class Rabit3 { public static void main(String[] args) { int i,a=1,b=1; System.out.print(a+" "+b+" "); for(i=1;i<=5;i++){ a=a+b; b=a+b; System.out.print(a+" "+b+" "); } } }
三、求最大公约数
1、方法一
穷举法
public class Gongyueshu_1 { public static void main(String[] args){ int a,b,t; System.out.println("输入两个整数"); Scanner scanner=new Scanner(System.in); a=scanner.nextInt(); b=scanner.nextInt(); t=a<b? a: b; //取ab中较小的数 while(!(a%t==0&&b%t==0)){ t--; } System.out.println(a+"和"+b+"的最大公约数为 "+t); } }
2、方法二
辗转相除法
public class Gongyueshu_2 { public static void main(String[] args) { int a,b,r,a1,b1; System.out.println("请输入两个整数"); Scanner scanner=new Scanner(System.in); a=scanner.nextInt(); b=scanner.nextInt(); a1=a; b1=b; while(b!=0){ r=a%b; a=b; b=r; } System.out.println(a1+"和"+b1+"的最大公约数是 "+a); } }
3、方法三
相减法
public class Gongyueshu3 { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); int a,b; System.out.println("请输入两个整数"); a=scanner.nextInt(); b=scanner.nextInt(); if(a==b) { System.out.println("最大公约数是:" + a); }else{ while(a!=b){ if(a>b) a=a-b; else b=b-a; } System.out.println("最大公约数是:" + a); } } }
四、this()用法
1、介绍 之前上课老师讲到this这个关键字的时候,this.变量名倒是讲清楚了 ① 直接引用 this 指向当前对象本身 ② 避免重复 形参与成员变量重复,用this区分 ③ this( ) 引用构造函数
this(参数):调用本类中另一种形式的构造函数(应该为构造函数中的第一条语句)。
2、代码 ① Person类
② 主函数Main
下一篇:
通过Java读取csv文件内容