Factorial in C without conditionals, loops and arithmetic operators

SyncMaster picture SyncMaster · Mar 17, 2009 · Viewed 14.2k times · Source

How can I find the factorial of a number (from 1 to 10) in C, without using:

  • loop statements like for, while, and do while;
  • conditional operators like if and case; and
  • arithmetic operators like + , − , * , % , /, ++, −−?

FYI: I found this question in C aptitude.

Answer

Brian R. Bondy picture Brian R. Bondy · Mar 17, 2009

Since it is only 1 to 10, simply precompute it and store it in a simple int array of size 11. For the first element in the array put 1. It is not a valid input range for your problem but might as well be correct.

We need to store 11 elements instead of the 10 we need because otherwise we'd need to use operation "-" to get the right index. Subtraction is not allowed in your problem though.

int factorial(int x)
{
  return precomputedArray[x];
}