10道JAVA基础编程练习题

【程序1】

 

题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子对数为多少?

 

程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....

 

public class Prog1{

 

public static void main(String[] args){

 

int n = 10;

 

System.out.println("第"+n+"个月兔子总数为"+fun(n));

 

}

 

private static int fun(int n){

 

if(n==1 || n==2)

 

return 1;

 

else

 

return fun(n-1)+fun(n-2);

 

}

 

}

 

【程序2】

 

题目:判断101-200之间有多少个素数,并输出所有素数。

 

程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。

 

public class Prog2{

 

public static void main(String[] args){

 

int m = 1;

 

int n = 1000;

 

int count = 0;

 

//统计素数个数

 

for(int i=m;i<n;i++){

 

if(isPrime(i)){

 

count++;

 

System.out.print(i+" ");

 

if(count%10==0){

 

System.out.println();

 

}

 

}

 

}

 

System.out.println();

 

System.out.println("在"+m+"和"+n+"之间共有"+count+"个素数");

 

}

 

//判断素数

 

private static boolean isPrime(int n){

 

boolean flag = true;

 

if(n==1)

flag = false;

else{

for(int i=2;i<=Math.sqrt(n);i++){

if((n%i)==0 || n==1){

flag = false;

break;

}

else

flag = true;

}

}

return flag;

}

}

【程序3】

题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。

程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。

public class Prog3{

public static void main(String[] args){

for(int i=100;i<1000;i++){

if(isLotus(i))

System.out.print(i+" ");

}

System.out.println();

}

//判断水仙花数

private static boolean isLotus(int lotus){

int m = 0;

int n =

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

素养和地方

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值