Base:阶乘+九九乘法表
阶乘:
例如:
2的阶乘:1x2
4的阶乘:1x2x3x4
package com.wochat.controller;
public class MainClass {
public static void main(String[] args) {
long sum = 1;
int score = 10;
for (int i = 1; i <= score; i++) {
sum *= i;
}
System.out.println(sum);
}
}
10的阶乘:3628800
如果,求100的阶乘:93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
其值超出long的范围
import java.math.BigInteger;
int s=100;
BigInteger a=new BigInteger("1");
for (int i = 1; i <=s; i++) {
BigInteger b=new BigInteger(String.valueOf(i));
a=a.multiply(b);
}
System.out.println(a);
String s="93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000";
System.out.println(s.length());
100的阶乘是158位
当然,在阶乘这种问题下,递归是最装B的
无形的装叉最致命!
package com.wochat.controller;
public class MainClass {
public static void main(String[] args) {
System.out.println(vsum(10));
}
public static int vsum(int v){
int sum;
if (v<=1){
sum=v;
}
else{
sum=v*vsum(v-1);
}
return sum;
}
}
改动一下:
package com.wochat.controller;
public class MainClass {
public static void main(String[] args) {
System.out.println(vsum(-1));
}
public static int vsum(int v) {
if (v <= 1) {
return v;
} else {
return v * vsum(v - 1);
}
}
}
最为简单的九九乘法表
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <=9; j++) {
System.out.print(i+"x"+j+"="+i*j+"\t");
}
System.out.println();
}
1x1=1
2x1=2 2x2=4
3x1=3 3x2=6 3x3=9
4x1=4 4x2=8 4x3=12 4x4=16
5x1=5 5x2=10 5x3=15 5x4=20 5x5=25
6x1=6 6x2=12 6x3=18 6x4=24 6x5=30 6x6=36
7x1=7 7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49
8x1=8 8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64
9x1=9 9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <=i; j++) {
System.out.print(i+"x"+j+"="+i*j+"\t");
}
System.out.println();
}
对比一下两段代码,改动一下啊,就有不同的效果
这就是Java的神奇之处!