Вопрос

I have to make a factorial table for an assignment, and somewhere along the line my logic isn't right. Here's what I have so far.

public static void factors(int n) {
    int r = 1; //starts r as zero, as a basis for multiplication
    int t = n;
    int q;     //allows original number to be shown 
    while(n > 1) { // factorial calculation
        r= r * n;     
        n = n- 1; 
    }  
    while(t>0) {
        table(t,r);
        t=t-1;
    }
}

public static void table(int t, int r){
//  while(n>0)
    System.out.println(t+ "\t"+r);
//  n=n-1;

}

And here's the output.

15  1409286144
14  1409286144
13  1409286144
12  1409286144
11  1409286144
10  1409286144
9   1409286144
8   1409286144
7   1409286144
6   1409286144
5   1409286144
4   1409286144
3   1409286144
2   1409286144
1   1409286144
Это было полезно?

Решение

Start by getting one factorial, then worry about the table.

Names matter: "factors" isn't a good name for a factorial method.

Here's a naive, terribly inefficient implementation:

public class Factorial {

    private static Map<Integer, Long> memo = new ConcurrentHashMap<Integer, Long>();

    public static void main(String[] args) {
        for (int i = 0; i < 11; ++i) {
            System.out.println(String.format("n: %d n!: %d", i, factorial(i)));
        }
    }
    public static long factorial(int n) {
        long value = 1L;
        if (n > 1) {
            if (memo.containsKey(n)) {
                value = memo.get(n);
            } else {
                for (int i = 1; i <= n; ++i) {
                    value *= i;
                }
                memo.put(n, value);
            }
        }
        return value;
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top