How to print factorials 0-30 on the table

public static void main(String[] args) {

    int n = factorial(30);
    int x = 0;
    while (x <= 30) {
        System.out.println(x + " " + n);
        x = x + 1;
    }


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

I am trying to print something like this:

0 1
1 1
2 2
3 6
4 24
...etc, up to 30 (30!)

Instead, I get the following:

0 (30!)
1 (30!)
...etc, up to 30

In words, I can create a left column from 0 to 30, but I want it to print the factorial of numbers in the right column. With my code, it only prints factorial 30 in the right column. I want him to print factorials next to their corresponding number. How can I fix my code to do this?

+4
source share
2 answers

It is pretty simple. Instead of defining a variable, you call the updated method xevery time:

System.out.println(x + " " + factorial(x));

Please note that your cycle can be rewritten as a cycle for, which they are intended for:

for (int x = 0; x < 30; x++) {
    System.out.println(x + " " + factorial(x));
}

:

  • x++. x = x + 1, . . .
  • x (for (int x = ...)
  • n . , , , factorial(x).

. , int 30!. 265252859812191058636308480000000 - . long, . , BigInteger:

public BigInteger factorial(int n) {
    if (n == 0) {
        return BigInteger.ONE;
    } else {
        return new BigInteger(n) * factorial(n - 1);
    }
}

- BigInteger#toString() magic, main, , .

+10

@QPaysTaxes , , , .

- 1 0 1, 2 0, 1 2, 3 0, 1, 2 3 .. :

import java.math.BigInteger;

public class Main
{

    public static BigInteger factorial (int n) {   
        if (n == 0) {
            System.out.println("0 1");
            return BigInteger.ONE;
          } else {
            BigInteger x = BigInteger.valueOf(n).multiply(factorial(n - 1));
          System.out.println(n + " " + x);
            return x;
          }
      }
  public static void main(String[] args)
  {
    factorial(30);
  }
}

, :

import java.math.BigInteger;

public class Main
{
  public static void main(String[] args)
  {
    System.out.println("0 1");
    BigInteger y = BigInteger.ONE;
    for (int x = 1; x < 30; ++x) {
        y = y.multiply(BigInteger.valueOf(x));
        System.out.println(x + " " + y);
    }
  }
}

, Python:

def f(n):
    if not n:
        print(0, 1)
        return 1
    else:
        a = n*f(n-1)
        print(n, a)
        return a

_ = f(30)

, Python:

r = 1
for i in range(31):
    r *= i or 1
    print(i, r)
0

Source: https://habr.com/ru/post/1584990/


All Articles