How to write a factorial? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 9

How to write a factorial?

19th Oct 2017, 7:24 PM
Mr.Orange
Mr.Orange - avatar
12 Answers
+ 20
factorial(0) = 0 Test it double is a mistake. use the following Code: https://code.sololearn.com/c1eewyI6n2PH/?ref=app
27th Oct 2017, 11:25 PM
Worm
Worm - avatar
+ 19
you mean it should be 0 per definition. In my opinion that is wrong, because the factorial of a number is a multiplication from 1 up to the input or from input down to 1. If anybody use an input of 0 or a negativ number, it returns 0. So the return of 0 is an error and no result. You have posted a link from wikipedia, where is described, that the factorial of 0 ist 0 per definition. But that is (in my opinion) a discrepancy to the definition of the factorial. If you multiply something with 0, the result is 0.
28th Oct 2017, 9:13 AM
Worm
Worm - avatar
27th Oct 2017, 8:27 AM
Worm
Worm - avatar
+ 15
#include<stdio.h> #include<string.h> #include<math.h> unsigned factorial (int n) { if (n==0 || n==1) return 1 ; else return n*(factorial(n-1) ); } void main () { int n ; printf("enter a number"); scanf ("%d", &n); printf ("answer : %d!= %u ",n,factorial(n)); }
6th Dec 2017, 1:37 PM
Anon Fox
Anon Fox - avatar
19th Oct 2017, 7:36 PM
Bohdan
Bohdan - avatar
+ 9
Use a loop (preferably a for loop) and a variable to store the answer. The variable can be by default 1. Multiply the variable being incremented in the loop by the answer. Make the loop continue incrementing by 1 until the number you want the factorial of. The loops variable can start at 2.
19th Oct 2017, 7:26 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
int factorial(int n){ if(n<=0) return 1; return n*factorial(n-1); }
20th Oct 2017, 12:03 AM
Chriptus13
Chriptus13 - avatar
+ 2
@Worm why do you return a double? And factorial(0)=1
27th Oct 2017, 11:03 PM
Chriptus13
Chriptus13 - avatar
28th Oct 2017, 12:10 AM
Chriptus13
Chriptus13 - avatar
17th Nov 2017, 9:28 AM
#RahulVerma
#RahulVerma - avatar
+ 1
https://code.sololearn.com/cu00VM8khFtr/?ref=app
1st Jun 2018, 8:15 PM
Shuaib Nuruddin
Shuaib Nuruddin - avatar
0
https://code.sololearn.com/cq48LPYvoenL/?ref=app This will help you to solve the factorial problem
21st Dec 2018, 3:52 PM
Soniya Kulkarni
Soniya Kulkarni - avatar