本文最后更新于:1 年前
递归阶层算法、非递归阶层算法
扩展①:求阶层的和
扩展②:寻找最高阶、打印阶层的计算过程
非递归阶层算法
import java.util.Scanner;
public class UnRecurrenceFactorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("input:");
int n = sc.nextInt();
int a = 1;
while(n != 1){
a = a*n;
n--;
}
System.out.println(a);
sc.close();
}
}
递归阶层算法
public class RecurrenceFactorial {
public static void main(String[] args) {
long fac = fac(k);//修改k的值即可
System.out.println("n的阶乘为:" + fac);
}
public static long fac(int n){
if(n == 1){
return 1;
}else{
return fac(n-1) * n;
}
}
}
扩展①:求阶层的和
🔺计算 1!+2!+3!+···+k! 的值:
public static void main(String[] args) {
int i,j;
long sum = 0;
for(i = 1; i <= k; i++){ //修改k的值即可
int t = 1;
for(j = 1; j <= i; j++){
t *= j;
}
sum += t;
}
System.out.println(sum);
}
扩展②:寻找最高阶、打印阶层的计算过程
🔺题目:
指定一个整型数MAX,试编写一个程序求满足1!+2!+3!…+n!<=MAX 的最大整数n。并把满足条件的求和式子和找到的最大整数n打印输出。
示例1:MAX=111时,输出
1!+2!+3!+4!=33
满足条件的最大整数:4
示例2:MAX=9876
1!+2!+3!+4!+5!+6!+7!=5,913
满足条件的最大整数:7
🔺代码:
import java.util.Scanner;
public class Du {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("the value of MAX:");
int MAX;
MAX=input.nextInt();
System.out.println("满足条件的最大整数:"+SUM(MAX));
input.close();
}
public static int SUM(int MAX) {
int i = 0,j;
long sum = 0;
for(i = 1; i <= 10; i++){
int t = 1;
for(j = 1; j <= i; j++){
t *= j;
}
sum += t;
if(sum>MAX)
break;
}
Print(i-1);
return i-1;
}
/*打印阶层的计算过程*/
public static void Print(int k) {
int i,j;
long sum = 0;
for(i = 1; i <= k; i++){ //修改k的值即可
int t = 1;
for(j = 1; j <= i; j++){
t *= j;
}
System.out.printf("%d! + ",i);
sum += t;
}
System.out.print("\b\b= "+ sum);//退两个,删去最后一个+
System.out.println();
}
}
🔺截图:
我的文章、代码简单,这里有更详细文章,见大佬👉Java实现n阶阶乘的计算
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!