patdybalski
patdybalski

Reputation: 15

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));
    }
}

Upvotes: 1

Views: 912

Answers (5)

Py-Coder
Py-Coder

Reputation: 2234

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;
}

Upvotes: 1

eftshift0
eftshift0

Reputation: 30212

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.

Upvotes: 1

Mohit
Mohit

Reputation: 1295

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! = n x (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);
}

Upvotes: 1

nissim abehcera
nissim abehcera

Reputation: 831

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));
}
}`

Upvotes: 2

Andronicus
Andronicus

Reputation: 26046

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);
}

Upvotes: 3

Related Questions