1. 古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一
对兔子,假如兔子都不死,问每个月的兔子总数为多少?
import java.util.Scanner;
public class Homework {
public static void main(String[] args) {
System.out.println("请月份数:");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println("兔子总数:"+sum(n)*2);
}
public static int sum(int month){
if(month!=1&&month!=2) {
if(month!=3) {
return sum(month-1)+sum(month-2);
}
else return 2;
}
else return 1;
}
}
2. 判断101-200之间有多少个素数,并输出所有素数。
素数又叫质数,就是除了1和它本身之外,再也没有整数能被它整除的数。也就是素数只有两个因子。
public class Homework {
public static void main(String[] args) {
t2();
}
public static void t2(){
for (int i = 101; i <=200 ; i++) {
boolean flag = false;
for (int j = 2; j < i; j++) {
if (i % j == 0){
break;
}
flag = true;
}
if (flag){
System.out.println(i);
}
}
}
}
3. 打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:
153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
public class Homework {
public static void main(String[] args) {
t3();
}
public static void t3 (){
for (int i = 100; i < 1000; i++) {
if (i == Math.pow(i%10,3)+Math.pow(i /10%10,3)+Math.pow(i/100,3)){
System.out.println(i);
}
}
}
}