I am attempting to create a C code that finds the factorial of a integer so that I may convert my code to assembly language. My code seems to 'multiply' the second integer twice. i.e. 5*4*4*3... I cannot seem to find out why. Help please!
#define N 5
int main() {
int j = 0;
int i = 0;
int num1 = N;
int num2 = N - 1;
int sum = 0;
while (num2 != 0) {
while (j < num2) {
sum += num1;
j++;
}
j = 0;
printf("%d\n", sum);
printf("--------------\n");
--num2;
num1 = sum;
}
printf("--->%d", sum);
}
Erroneous Output:
20
--------------
80
--------------
240
--------------
480
--------------
480
Here's the machine state, from which you should be able to see why your algorithm isn't right:
PS Another, perhaps better, way to think about this is that your mathematics is wrong. You're doing three multiplications (repetitions of the inner loop--multiplying by an integer using repeated addition). But you also do three additions of the products. Those sums tell you that you're not computing a factorial.
The steps for the computation are incorrect: it is simpler to start from the low factors to the larger ones.
Here is a corrected version:
Output:
If you add some intermediate debugging output you'll find where you went wrong:
This produces:
You can see here that the problem is that the
sum
value is carried forward from each pass through the loop, when it should really be reset to 0 each time. So addat the top of the
while
loop.So your final code becomes:
Best of luck.
Check this...
https://code.sololearn.com/cKWo4Cc0GKd1
I've created it using JAVA