Skip to content

Instantly share code, notes, and snippets.

@wbruno
Created April 6, 2015 23:22
Show Gist options
  • Save wbruno/96aa3b0b42ed38856b37 to your computer and use it in GitHub Desktop.
Save wbruno/96aa3b0b42ed38856b37 to your computer and use it in GitHub Desktop.
fatorial.c
/**
* 2.Faça uma função que receba um número N e retorne a soma dos algarismos de N!.
* Ex: se N = 4, N! = 24. Logo, a soma de seus algarismos e 2 + 4 = 6.
*/
#include <stdio.h>
#include <string.h>
int fatorial(int n) {
int fat = 1;
for (int i = 1; i<=n; i++) {
fat *= i;
}
return fat;
}
int sumDigits(int num) {
int sum = 0;
char buffer[10];
sprintf(buffer, "%d", num);
for (int i = 0; i<strlen(buffer); i++) {
int charInt = buffer[i] - '0';
sum += charInt;
}
return sum;
}
int main() {
int n = 7;
int fat = fatorial(n);
int sum = sumDigits(fat);
printf("n: %d\n", n);
printf("fat: %d\n", fat);
printf("sum: %d\n", sum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment