Hey guys, I'm pretty new to C and have managed (with a little help) to come up with the following code. The code works and comes out with a correct factorial up to 69! (But this is fine I only need it to work up to 60). I was wondering if this could be simplified or optimized in any way. Thanks guys!
insert
Code:
#include <stdio.h>
int main(){
int number[100]; /*Created array of size 100 */
int n=34; /*19931120 summed to make 34 */
int i;
for(i=1; i<=n; i++) {
int j;
if (i==1) {
for(j=0; j<99; j++) {
number[j] = 0; /*Creates base case where all indexes are populated */
} /*with 0s, Except last index which is populated with 1 */
number[99] = 1;
} else {
for(j=0; j<=99; j++) {
number[j] = number[j] * i; /*Multiplies index by i */
if(number[j] >= 10) {
number[j-1] = number[j-1] + number[j] / 10; /*If multiplied index is */
number[j] = number[j] % 10;
} /*greater than 10, adds tens and hundreds to the index to the left. */
} /*Replaces multiplied index with unit alone Loops to multiply all indexes */
for(j=99; j>=0; j--) {
if(number[j] >= 10) { //Looping through all the indexes starting at the */
number[j-1] = number[j-1] + number[j] / 10;
number[j] = number[j] % 10; /*end, checks for any greater than 10 */
} /*If greater than 10 splits tens and adds to the index to the left. */
} /*Leaving single digits in each index. */
}
}
int total = 0;
for(i=0; i<100; i++) {
total = total + number[i]; /*Sums all indexes for printing. */
printf("%i", number[i]); /*Printing each index so factorial can be seen. */
}
printf("\n"); /*Prints N and sum of the digits of factorial. */
printf("N is %i, sum is %i\n", n, total);
return 0;
}