简体   繁体   中英

Java Factorial Program

I can't figure out what I'm missing on my code. Any help will be greatly appreciated. I'm new in coding and I'm just doing some practice. Thank you!

import java.util.Scanner;
import java.lang.Math;

public class Factorial {

    public static Scanner sc;

    public Factorial() {
    }

    int factorial(int n) {
        for (int j = n - 1; j > 0; j--) {
            int factorial = factorial(0) * j;
        }
        return factorial(0);
    }

    public static void main(String[] args) {

        System.out.print("Enter a number to find its factorial: ");
        sc = new Scanner(System.in);
        int myNumber = sc.nextInt();

        Factorial myFactorial = new Factorial();
        System.out.println(myFactorial.factorial(myNumber));
    }
}

You're missing the corner case (for 0):

int factorial(int n) {
    if (n == 0) return 1;
    for (int j = n - 1; j > 0; j--) {
        int factorial = factorial(0) * j;
    }
    return factorial(0);
}

In recursive mode : `

import java.util.Scanner;
import java.lang.Math;




class Factorial {

public static Scanner sc;


public static int factorial(int n) {
    if(n==0)return 1;
    return n*factorial(n-1);
}

public static void main(String[] args) {

    System.out.print("Enter a number to find its factorial: ");
    sc = new Scanner(System.in);
    int myNumber = sc.nextInt();

    //Factorial myFactorial = new Factorial();
    System.out.println(factorial(myNumber));
}
}`

Well.... regardless of what you provide on n, you always return factorial(0) which ends up creating an endless loop of calls to factorial so I guess your stack is getting hammered and getting an Stack Overflow error, right? I think that's where the error is.

For every recursive function, you must need to write a base case else it will end up doing recursion and at the end it will cause stack overflow error(not the name of this site, it is an error), which is what you are missing right there in your algorithm.

For finding factorial recursively

Mathematically

n! = nx (n - 1)! and the base case is 0! = 1

In Java

// somewhere in your class
int factorial(int n) {
   // base case
   if (n == 0) return 1;

   // recursion
   return n * factorial(n-1);
}

Replace this code in your code:

 int factorial=1;
int factorial(int n) {
   for (int j = 1; j <= n; j++) {
       factorial = factorial * j;
    }
    return factorial;
}

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