Search code examples
javafactorial

find Factorial of no. It is working fine but i am not able to understand why its giving me factorial 0 for no 56,89,77 and other some numbers


This is my code for factorial program. it is working fine but i am not able to understand why its giving me factorial 0 for no 56,89,77 and other some numbers.

private static void factorial() {
    int resultant = 1, i;
    System.out.println("Please Enter any number to find factorial : ");
    Scanner scan = new Scanner(System.in);
    int fact = scan.nextInt();
    for (i = 1; i <= fact; i++) {
        resultant = resultant * i;
    }
    System.out.println("Factorial of number : " + resultant);
}

Solution

  • Every even number that is part of the product contributes a trailing zero to the factorial. Actually to be more precise, the trailing zero count of a (unlimited precision) product is the sum of the trailing zero counts of the inputs. In finite precision the number of trailing zeroes is obviously limited by the size of the number.

    So eventually, and this happens pretty quickly, the number of trailing zeroes becomes greater than or equal to 32, in which case all bits of an int would be zero. The same thing of course happens with long, a little later, at 64 trailing zeroes. And some time before that, even though the result is not totally zero yet, it would already have stopped matching what the result would have been in unlimited precision.

    For example 34! in hexadecimal is

    de1bc4d19efcac82445da75b00000000
    

    The 8 least significant digits would be what you would get if you computed it with 32 bit integers, and all those digits are zero.