简体   繁体   中英

Java Nested While Loops and Factorials Beginner

I'm working on nest while loops. I began with an initial while loop, that printed out the factorial of a given number. The code for that is below. I am now trying to to add the second loop, which would 10 numbers, (ie if the number 4 was inputted, it would print out the factorial for numbers 4 through to 14). I know the loop should begin above what I already have, but I don't really know where to go from there. I've inserted what I think is the beginning of the first loop. I'm new to coding so any and all help is appreciated

Existing code:

import java.util.Scanner;

public class MyClass 
{
    public static void main(String args[]) 
    {
        Scanner myScanner = new Scanner(System.in)

        while (count <10)
        {
            int number = myScanner.nextInt();
            int fact = 1;
            int i = 1;

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

-You need to move the number = myScanner.nextInt() outside of the loop so that it won't ask for new input every iteration.

-You need to define count ( int count = 0 ;)

-Loop until count is <= 10.

-Increment count and number at the end of the loop:

Scanner myScanner = new Scanner(System.in);
int count = 0;
int number = myScanner.nextInt();
while (count <=10) {

     int fact = 1;
     int i = 1;

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

Output: (With 4 as input)

Factorial of 4 is: 24
Factorial of 5 is: 120
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
Factorial of 9 is: 362880
Factorial of 10 is: 3628800
Factorial of 11 is: 39916800
Factorial of 12 is: 479001600
Factorial of 13 is: 1932053504
Factorial of 14 is: 1278945280

However we can optimize this a lot. 5! is equal to 4! * 5. So knowing this we can simply not reset i and fact inside the loop. If we enter 4, after the first iteration, fact will be equal to 4!, and i will be equal to 5. If simply don't reset them, on the next iteration we will simply multiply fact (4!) by 5. Then i will become six and the while loop will terminate. Then this will continue until the outer while loop terminates.

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

With 4 as the input this will reduce the amount of iterations in the inner while loop from 99 to 14.

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