#include <stdio.h> int main() { int number; int x = 1; scanf("%d", &number); if ( number < 0 ) { printf("-1\n"); } else { for ( int i = 0; i < number; i++ ) { x *= ( i + 1 ); } printf("%d\n", x); } return 0; } 

Option number 2

 #include <stdio.h> int factorial(int n) { if ( n < 0 ) { return -1; } if ( n <= 1 ) { return 1; } return n * factorial(n-1); } int main() { int m; scanf("%d", &m); printf("%d\n", factorial(m)); return 0; } 

    2 answers 2

    You can rewrite option 1 like this:

     #include <stdio.h> int main() { int number, x = 1; scanf("%d", &number); if ( number < 0 ) x = -1; else { for ( ; number > 1; number-- ) x *= number; } printf("%d\n", x); return 0; } 

    But this is not really that optimization.

    • Thanks helped!) - arcs_host

    Calculation of factorial modulo p in time O (p LOG N) , where LOG is on the basis of p . (p is simple)

      int res = 1; while (n > 1) { res = (res * ((n/p) % 2 ? p-1 : 1)) % p; for (int i=2; i<=n%p; ++i) res = (res * i) % p; n /= p; } return res % p; 

    Detailed description here .

    Here is the code optimization:

     long f(long a) {return (a>1?a*f(a-1):1);} Тогда f(x) = x! 
    • And you can advice on my code?)) - arcs_host
    • one
      Your solution "in the forehead": as it is, and calculate. <br /> To speed up the calculation it is necessary to use other methods. Factorial is a function that grows very quickly, so it is advisable to consider factorial modulo, as in my answer. - megacoder
    • Thanks, I understand that, but the task was set like this, and you need to optimize this code ( - arcs_host
    • one
      Optimized for code size? - megacoder