Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public int factorial(int n) {
- int[] fact = {1, 1, 2, 6, 24, 120, 720, 5040, 40320,
- 362880, 3628800, 39916800, 479001600};
- return fact[n];
- }
- ans = 1
- for i = n down to 2
- ans = ans * i
- next
- public double factorial(int n) {
- double result = 1;
- for(double i = 2; i<=n; ++i) {
- result *= i;
- }
- return result;
- }
- int factorial(int i) {
- static int factorials[] = {1, 1, 2, 6, 24, 120, 720,
- 5040, 40320, 362880, 3628800, 39916800, 479001600};
- if (i<0 || i>12) {
- fprintf(stderr, "Factorial input out of rangen");
- exit(EXIT_FAILURE); // You could also return an error code here
- }
- return factorials[i];
- }
- C++ C#
- ---------------------
- Iterative 1.0 1.6
- Lookup .28 1.1
- Recursive 2.4 2.6
- C++ C#
- ---------------------
- Iterative 1.0 2.9
- Lookup .16 .53
- Recursive 1.9 3.9
- long fact(int n) {
- long x = 1;
- for(int i = 1; i <= n; i++) {
- x *= i;
- }
- return x;
- }
- int total = 1
- loop while n > 1
- total = total * n
- n--
- end while
- def fact(n): return (reduce(lambda x, y: x * y, xrange(1, n+1)))
- total = 1
- For i = 1 To n
- total *= i
- Next
- fac = 1 ;
- for( i = 1 ; i <= n ; i++){
- fac = fac * i ;
- }
- public int factorialNonRecurse(int n) {
- int product = 1;
- for (int i = 2; i <= n; i++) {
- product *= i;
- }
- return product;
- }
- #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;
- }
- long fact(int n)
- {
- long fact=1;
- while(n>1)
- fact*=n--;
- return fact;
- }
- long fact(int n)
- {
- for(long fact=1;n>1;n--)
- fact*=n;
- return fact;
- }
- //Note: many compilers have an upper limit on the number of recursive templates allowed.
- template <int N>
- struct Factorial
- {
- enum { value = N * Factorial<N - 1>::value };
- };
- template <>
- struct Factorial<0>
- {
- enum { value = 1 };
- };
- // Factorial<4>::value == 24
- // Factorial<0>::value == 1
- void foo()
- {
- int x = Factorial<4>::value; // == 24
- int y = Factorial<0>::value; // == 1
- }
- int fact(int n){
- int r = 1;
- for(int i = 1; i <= n; i++) r *= i;
- return r;
- }
Add Comment
Please, Sign In to add comment