您的位置:首页 > 其它

The Third Day

2015-07-16 18:47 141 查看
随堂练习

目录

金字塔

Fibonacci数列

求兔子数

完全数

- 输出一个金字塔

package Test;

import java.util.Scanner;

public class Test_4 {
public static void main(String[] args) {
// 输出一个金字塔
System.out.println("请输入金字塔层数:");
Scanner sc=new Scanner(System.in);
int count=sc.nextInt();
for (int i=1; i <count; i++) {
for (int k = 1; k <count-i; k++) {
System.out.print(" ");
}
for (int j = 0; j < 2*i-1; j++) {
System.out.print("*");
}
System.out.println();
}
}
}


- 求Fibonacci数列的前20项

package Test;

public class Fibonacci {
public static void main(String[] args) {
// Fibonacci数列
//1 1 2 3 5 8 13
int a=1;
int b=1;
int temp=0;
System.out.println("Fibonacci数列的前20项为:");
System.out.print(a+"\t"+b+"\t");
for (int i =1; i <18; i++) {
temp=a+b;
a=b;
b=temp;
System.out.print(temp+"\t");
if ((i+2)%5==0) {
System.out.println();
}
}
}
}


- 求1000以内的完全数

package Test;

public class Test_3 {
public static void main(String[] args) {
// 求1000以内的完全数
for (int i = 1; i <= 1000; i++) {
int temp = 0;
for (int n = 1; n < i; n++) {
if (i % n == 0) {
temp += n;
}
}
if (temp == i) {
System.out.print(i + " ");
}
}
}
}


- 求兔子数

/* 生兔子问题
* 现有一对成熟兔子,一对
* 成熟兔子每月生一对兔子,
* 小兔子三个月成为成熟兔子。
* 问?20个月后有多少只兔子
*/
// 1 2 3 4 6 9
package Test;
public class Test_1 {
public static void main(String[] args) {
int a=1;
int b=2;
int c=3;
int temp=0;
System.out.print(a+"\t"+b+"\t"+c+"\t");
for (int i =4; i < 21; i++) {
temp=a+c;
a=b;
b=c;
c=temp;
System.out.print(temp+"\t");
if ((i+5)%5==0) {
System.out.println();
}
}
}
}


求1+3+7+···+2^20-1的和

package Test;

public class Test_2 {
public static void main(String[] args) {
// 1+3+7+...+(2的20次方-1)
int temp=0;
int a=1;
for (int i=1;i<21;i++) {
a*=2;
temp+=a-1;
}
System.out.println(temp+"");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: