JAVA作业:编写一个程序,求满足1+2!+3!+...+n!<=9876的最大整数n
发布网友
发布时间:2024-10-02 15:29
我来回答
共5个回答
热心网友
时间:2024-11-20 23:24
public
class
Test
{
public
static
void
main(String[]
args)
{
int
max
=
9876;
int
current
=
0;
int
index
=
1;
while
(current
<=
max)
{
current
+=
calc(index++);
System.out.println(current);
}
System.out.println("符合要求的最小整数是:"+(index-1));
}
public
static
int
calc(int
num)
{
int
result
=
1;
for
(int
i
=
1;
i
<=
num;
i++)
{
result
*=
i;
}
return
result;
}
}
热心网友
时间:2024-11-20 23:18
public class Test {
public static void main(String[] args) {
int max = 9876;
int current = 0;
int index = 1;
while (current <= max) {
current += calc(index++);
System.out.println(current);
}
System.out.println("符合要求的最小整数是:"+(index-1));
}
public static int calc(int num) {
int result = 1;
for (int i = 1; i <= num; i++) {
result *= i;
}
return result;
}
}
热心网友
时间:2024-11-20 23:23
public class TestNum {
public int jieCheng(int n){
if(n!=1)
return n*jieCheng(n-1);
else return 1;
}
public int testNum(int num){
int n=0;
int total=0;
while(total<=num){
n++;
System.out.println(n+"的阶乘是"+jieCheng(n));
total+= jieCheng(n);
}
return n;
}
public static void main(String[] args){
TestNum tn = new TestNum();
System.out.println(tn.testNum(9876));
}
}
热心网友
时间:2024-11-20 23:27
楼上的两个答案都不对。都忘了将 n -1 。
public class TestNFactorial {
public static void main(String[] args){
int target = 9876;
run(target);
}
private static void run( int target) {
int sum = 0 ;
int n=0;
while(sum <= target){
n++;
sum+=computeFactorial(n);
}
System.out.println("the n is : " +( n -1) );
}
private static int computeFactorial(int n) {
if(n==1|| n ==0 ){
return 1;
}else{
return n * computeFactorial( n-1 );
}
}
}
热心网友
时间:2024-11-20 23:22
public static void main(String[] args) {
System.out.println(t(9876));
}
public static int t(int max) {
return t3(1, 0, max);
}
public static int t3(int n, int y, int max) {
y = y + jc(n);
if (y > max) {
return n - 1;
}
return t3(n + 1, y, max);
}
public static int jc(int n) {
if (n != 1)
return n * jc(n - 1);
return 1;
}
最后结果为 7