目录
1、斐波那契数
2、水仙花数
3、顺序输出
4、阶层的和
5、乘法表
1、斐波那契数
使用递归方法来实现
import java.util.Scanner;
public class Recursion {
public static int fib(int n) {
if(n == 1 || n == 2){
return 1;
}else{
return fib(n-1) + fib(n-2);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(fib(n));
}
}
使用循环迭代方法,这个更快的实现
import java.util.Scanner;
public class Recursion {
public static int fib2(int n) {
if(n == 1 || n == 2) {
return 1;
}else {
int f1=1;
int f2=1;
int f3=0;
for (int i = 3; i <= n; i++) {
f3 = f1 + f2;
f1 = f2;
f2 = f3;
}
return f3;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(fib2(n));
}
}
2、水仙花数
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
int a = i/100;
int b = i/10%10;
int c = i%10;
if(i == a*a*a+b*b*b+c*c*c) {
System.out.println(i+"是水仙花数");
}
}
}
}
3、顺序输出
import java.util.Scanner;
public class Main {
public static void everOne(int n) {
if(n < 9){
System.out.print(n+" ");;
}else{
everOne(n/10);
System.out.print(n%10+" ");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
everOne(n);
}
}
4、阶层的和
import java.util.Scanner;
public class Main {
public static int facSum(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum = sum + fac(i);
}
return sum;
}
public static int fac(int n) {
if(n == 1){
return 1;
}else {
return n*fac(n - 1);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int tmp = fac(n);
int sum = facSum(n);
System.out.println(sum);
}
}
5、乘法表
import java.util.Scanner;
public class main {
public static void timesTable(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i+"*"+j+"="+i*j+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
timesTable(n);
}
}
|