How would you write a non-recursive algorithm to calculate factorials?

后端 未结 22 990
不思量自难忘°
不思量自难忘° 2020-12-10 11:39

How would you write a non-recursive algorithm to compute n!?

22条回答
  •  青春惊慌失措
    2020-12-10 12:10

    assuming you wanted to be able to deal with some really huge numbers, I would code it as follows. This implementation would be for if you wanted a decent amount of speed for common cases (low numbers), but wanted to be able to handle some super hefty calculations. I would consider this the most complete answer in theory. In practice I doubt you would need to compute such large factorials for anything other than a homework problem

    #define int MAX_PRECALCFACTORIAL = 13;
    
    public double factorial(int n) {
      ASSERT(n>0);
      int[MAX_PRECALCFACTORIAL] fact = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 
                    362880, 3628800, 39916800, 479001600};
      if(n < MAX_PRECALCFACTORIAL)
        return (double)fact[n];
    
      //else we are at least n big
      double total = (float)fact[MAX_PRECALCFACTORIAL-1]
      for(int i = MAX_PRECALCFACTORIAL; i <= n; i++)
      {
        total *= (double)i;  //cost of incrimenting a double often equal or more than casting
      }
      return total;
    
    }
    

提交回复
热议问题