【程序1】
* 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一
* 对兔子,假如兔子都不死,问每个月的兔子总数为多少?
* 1.程序分析: 兔子的规律为数列2,2,4,6,10,16,26,42,68...
import java.util.Scanner;
public class RubbitsumQuestion {
public static void main(String[] args) {
while(true){ System.out.print("请输入您要查看的月份:");
Scanner scan=new Scanner(System.in); int month=3;
try{
month=scan.nextInt();
if(month<=0){
throw new Exception();
}
}catch (Exception e) {
System.out.print("您的输入有误,请重新输入:");
continue;
}
int rubbitsum=computeCount(month);
System.out.println("第"+month+"个月时,兔子总数为:"+rubbitsum);
}
}
//递归算法计算裴波纳契级数
public static int computeCount(int month){
if(month==1||month==2){
return 2;
}else{
return computeCount(month-1)+computeCount(month-2);
}
}
}
package com.supersoft.exercise;
/**
* @author JamesLiu
*
* 【程序2】
* 题目:判断101-200之间有多少个素数,并输出所有素数。
* 1.程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,
* 则表明此数不是素数,反之是素数。
*/
public class ProgramEx2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i=101; i<200; i+=2) {
boolean f=true;
for (int j=2; j<i;j++) {
if(i%j == 0) {
f = false;
break;
}
}
if (!f) {
continue;
}
System.out.println(" "+i);
}
}
}
package com.supersoft.exercise;
/**
* @author JamesLiu
*
*【程序3】
* 题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:
* 153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
* 1.程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位
*/
public class ProgramEx3 {
public static void main(String[] args) {
for (int i=100; i<=999; i++) {
int a = i/100;
int b = i%100/10;
int c = i%10;
if (i == a*a*a + b*b*b + c*c*c) {
System.out.println(i);
}
}
}
}
package com.supersoft.exercise;
/**
* @author JamesLiu
*
*【程序4】
* 题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
* 程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:
* (1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。
* (2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,重复执行第一步。
* (3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。
*/
public class ProgramEx4 {
public static void main(String[] args) {
int k=90;
System.out.print("90=");
for (int n=2; n<=k; n++) {
if (k%n == 0) {
if (n != k) {
System.out.print(n+"*");
k = k/n;
n = 2;
}
else {
//System.out.print("90=");
System.out.print(k);
}
}
}
}
}