简体   繁体   中英

Factorial program using for loops

I am an AP Computer Science student and I was wondering how to finish up my factorial code using for loops. Here is what I have so far:

import java.util.Scanner;
public class Factorial 
{

    public static void main(String[] args) 
    {
        int num;
        int factorial = 1;
        int i;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number: ");
        num = input.nextInt();
        for(i = 1; i <= num; i++)
        {
            factorial *= i;
        }
        System.out.println("!"+num+"="+factorial);

I tested it using eclipse and it worked for all integers until (and including) 12. When I entered 13, it gave me an incorrect number. Can someone explain to me why that is and how to rectify it?

Also, the assignment says I need to print out the numbers that I'm multiplying in addition to the answer (ie if num = 5, then the output is 5! = 5*4*3*2*1 = 120) . Can someone point me in the right direction for that issue?

Rahul first change Int to BigInt to fix the issue for numbers after 12 because Int max value is 2,147,483,647. Then change your for loop to below for printing in desired manner.

String a = “”;

for(i = 1; i <= num; i++)
    {
        factorial = factorial.multiply(i);

        if(i==1)
              a = String.valueOf(i)
        else
             a = a + "*" + String.valueOf(i)

    }
    System.out.println("!"+num+"="+ a + "="+factorial);

This prints the numbers as 1*2*3*5... if you want in reverse 5*4*3... then simply change the for loop to for(i=num;i>=1;i--)

This is because 13's factorial is greater than integer's MAX_VALUE ( 2147483647 ). As a result MAX_VALUE is subtracted from supposed result 6227020800 which is greater than MAX_VALUE ( 4079537153 ). This result is again subtracted from MAX_VALUE and the result 1932053504 is printed.

The above is only an explanation. As the comment below indicates, in practice the number is not subtracted by the JVM rather it overflows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM