1.古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数是多少对?
程序分析:每个月兔子总数是1,1,2,3,5,8,13,21……发现规律,从第三个月开始,每个月的兔子总数是前两个月的兔子总数的和。(这个数列其实是斐波那契数列)
public class Question1 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("请输入第几个月:");
int month = in.nextInt();
int temp1 = 1; //表示上上个月的兔子总数
int temp2 = 1; //表示上个月的兔子总数
int count = 0;
if(month == 1){
System.out.println("该月兔子总数是:" + 1);
}else if(month == 2){
System.out.println("该月兔子总数是:" + 1);
}else{
for(int i=0; i
2. 判断101-200之间有多少个素数,并输出所有素数?
程序分析:素数是指只有1和它本身两个正因数的自然数,给出一个自然数,我们只需要从2除到该自然数的平方根,如果都不能整除,说明该自然数为素数。
public class Question2 {
public static void main(String[] args){
int count = 0;
for(int i=101; i<=200; i++){
if(isPrimeNumber(i)){
count++;
System.out.println(i);
}
}
System.out.println("----->总共有" + count + "个素数");
}
/**
* 判断一个数是不是素数
*
* @return true说明n是素数,false说明n不是素数
*/
private static boolean isPrimeNumber(int n){
if(n == 1){
return false;
}
for(int i=2;i<=Math.sqrt(n);i++){
if(n%i == 0){
return false;
}
}
return true;
}
}
3.打印出所有的“水仙花数”,所谓“水仙花数”是指一个三位数,其各位数字立方和等于该数本身。例如:153就是一个“水仙花数”因为153=1的三次方+5的三次方+3的三次方?
程序分析:我们需要获取到一个给定三位数的个位数、十位数、百位数,然后进行相等性判断即可。
public class Question3 {
public static void main(String[] args) {
for(int i=100; i<=999; i++){
if(isNarcissusFew(i)){
System.out.println(i);
}
}
}
/**
* 判断一个三位数是否是“水仙花数”
*
* @param n
* @return true 说明n是“水仙花数”,false说明n不是“水仙花数”
*/
private static boolean isNarcissusFew(int n) {
int singleDigit = (n % 100) % 10; // 取个位数
int tensDigit = (n / 10) % 10; // 取十位数
int hundredsDigit = n / 100; // 取百位数
int cube = singleDigit * singleDigit * singleDigit + tensDigit
* tensDigit * tensDigit + hundredsDigit * hundredsDigit
* hundredsDigit;
if(cube == n){
return true;
}else{
return false;
}
}
}
4.将一个正整数分解质因数。例如:90=2*3*3*5。
程序分析:首先判断给定的正整数n是否是合数,如果不是,则打印n是素数,无法分解;如果n是合数,则按一下步骤完成:
(1)如果质数k恰等于n,说明分解质因数过程已经结束,将List中的质因数打印即可;
(2)2
(3)如果n不能被k整除,则用k+1作为k的值,重复执行第二步。
public class Question4 {
static LinkedList primeFactorList;
public static void main(String[] args) {
primeFactorList = new LinkedList();//用来存质因数
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if(isPrimeNumber(n)){
System.out.println(n + "是素数,无法分解!!!");
return;
}
solve(n);
if(primeFactorList.size()>1){
for(int i=0 ; i
5.输入两个正整数m和n,求其最大公约数和最小公倍数。
程序分析:最大公约数是指两个或多个整数共有约数中最大的一个,最小公倍数是指几个数共有的倍数中最小的一个。我们一般利用辗转相除法获取两个数的最大公约数,然后通过m*n/gcd获取两个数的最小公倍数。
public class Question5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt(); //获取输入值a
int b = sc.nextInt(); //获取输入值b
int gcd = calcGCD(a, b); //计算最大公约数
int lcm = calcLCM(a, b, gcd); //计算最小公倍数
System.out.println("(a,b)=" + gcd);
System.out.println("[a,b]=" + lcm);
}
/**
* 运用辗转相除法计算a和b的最大公约数
* 例如,求(319,377):
∵ 377÷319=1(余58)
∴(377,319)=(319,58);
∵ 319÷58=5(余29),
∴ (319,58)=(58,29);
∵ 58÷29=2(余0),
∴ (58,29)= 29;
∴ (319,377)=29.
*
* @param a
* @param b
* @return
*/
private static int calcGCD(int a, int b){
int temp;
if(a