2016-10-09 4 views
-3

이 내 임무의 일부와 나는 아래를 완료 5, 7계승 계산, 어디서 잘못 되었습니까?

의 계승을 계산하기 위해 질문을 받았다 :

import java.util.Scanner; 
    public class Factorial { 
     public static void main(String [] args) 
     { 
      System.out.println("Please enter a number: "); 
      Scanner input=new Scanner(System.in); 
      int number=input.nextInt(); 
      int i,fact=1; 

       for(i=1;i<=number;i++){  
        fact=fact*i;  
       }  
       System.out.println("Factorial of " + number + " is: " + fact);   
     } 
    } 

그것은 (120 및 5040을 결과) 5, 7 일했다. 하지만 교수님이 와서 20과 987654321로 테스트 해 보니 결과는 -2102132736과 0을 반환합니다.

왜 그런가요?

P. 987654321의 경우 응용 프로그램을 크래시하거나 오류가 발생하기 때문에 결과가 커질 것으로 생각했습니다.

+4

정수 오버플로 (크래시 없음). 'fact'를'long' (또는'BigInteger')으로 변경하십시오. –

+0

다른 사람이 큰 번호를 사용하는 경우 "Int"대신 "Long"을 사용해야합니다. 그러나 여전히, 987654321의 계승 결과가 0을 반환하는 이유는 무엇입니까? – Meruemu

+1

[Java가 10에서 99까지의 모든 숫자의 곱이 0이라고 생각하는 이유는 무엇입니까?] (// stackoverflow.com/q/26375932) – Tom

답변

1

5040!이므로 매우 (심지어는 long 오버플로)입니다. BigInteger과 같이 사용하십시오.

System.out.println("Please enter a number: "); 
Scanner input = new Scanner(System.in); 
int number = input.nextInt(); 
BigInteger fact = BigInteger.ONE; 
for (int i = 2; i <= number; i++) { // <-- x * 1 = x 
    fact = fact.multiply(BigInteger.valueOf(i)); 
} 
System.out.println("Factorial of " + number + " is: " + fact); 
+0

987654321의 계승 결과를 얻을 수 있습니까? – saka1029

+0

@ 예. 예. 그것은 아주 아주 큽니다. –

+1

이 알고리즘은 많은 수를 처리 할 수 ​​있지만 속도 측면에서는 매우 비효율적입니다. 더 똑똑한 알고리즘을 사용하는 것이 더 좋습니다 (http://www.luschny.de/math/factorial/FastFactorialFunctions.htm). – 4castle

2

이 코드는 문제를 해결할 수 있습니다. It is taken from here

class BigFactorial 
{ 
    static void factorial(int n) 
    { 
     int res[] = new int[300]; 

     // Initialize result 
     res[0] = 1; 
     int res_size = 1; 

     // Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n 
     for (int x=2; x<=n; x++) 
      res_size = multiply(x, res, res_size); 

     System.out.println("Factorial of given number is: "); 
     for (int i=res_size-1; i>=0; i--) 
      System.out.print(res[i]); 
    } 

    // This function multiplies x with the number represented by res[]. 
    // res_size is size of res[] or number of digits in the number represented 
    // by res[]. This function uses simple school mathematics for multiplication. 
    // This function may value of res_size and returns the new value of res_size 
    static int multiply(int x, int res[], int res_size) 
    { 
     int carry = 0; // Initialize carry 

     // One by one multiply n with individual digits of res[] 
     for (int i=0; i<res_size; i++) 
     { 
      int prod = res[i] * x + carry; 
      res[i] = prod % 10; // Store last digit of 'prod' in res[] 
      carry = prod/10; // Put rest in carry 
     } 

     // Put carry in res and increase result size 
     while (carry!=0) 
     { 
      res[res_size] = carry%10; 
      carry = carry/10; 
      res_size++; 
     } 
     return res_size; 
    } 

    // Driver program 
    public static void main(String []args) 
    { 
     factorial(100); 

    } 

} 
1

이 때문에 당신이 저장하고 결과를 인쇄 촬영 한 용기는 큰 정수 (I 20의 계승을 의미) 보유 할 수있는 능력을 가지고 있지 않는다는 사실이다. 그래서, 당신은 더 큰 컨테이너가 필요합니다. 다른 사람들이 이미 제안했듯이 BIGINTEGER를 사용할 수 있습니다.

관련 문제