diff --git a/math/krishnamurthy.c b/math/krishnamurthy.c index cc65ef9122..3ad3f2f768 100644 --- a/math/krishnamurthy.c +++ b/math/krishnamurthy.c @@ -1,29 +1,39 @@ -#include +#include // For I/O ops +#include //For test cases -/* - - * A krishnamurthy number is a number where the sum of - the factorial of its digits is equal to the number itself +/** +MAIN DESCRIPTION: - For example, 145 = 1! + 4! + 5! - but 13 != 1! + 3! + * @description a krishnamurthy number is + * a number whose sum of the factorial of digits + * is equal to the number itself. - * For more information, visit https://www.geeksforgeeks.org/problems/krishnamurthy-number1323/1 + * @example 145 = 1! + 4! + 5! + * @reference https://www.geeksforgeeks.org/problems/krishnamurthy-number1323/1 */ +/** + * @description n! = n*(n-1)*(n-2)*...*1 + * @brief calculates the factorial of a number + * @param n the number we want to calculate the factorial + * @return an integer representing the factorial of n + */ int factorial(int n){ - //Simple function returning the factorial of n - if (n<2){ return n; } return n*factorial(n-1); } +/** + * @brief Calculates the sum of the factorial of each digit + * @param n the number to calculate the sum of the factorial of its digits + * @param sum the sum variable to be incremented + * @returns an integer representing that sum + */ int get_digit(int n, int sum){ - // Function returning the sum of the factorial of the digits if (n<10){ return sum+factorial(n); @@ -35,21 +45,33 @@ int get_digit(int n, int sum){ } } -void krishnamurthy(int n){ +/* + * @brief Verifies if a given number + * is a krishnamurthy number + * @param n the number to be verified as a krishnamurthy number + * @returns 1 if n is a krishnamurthy number + * @returns 0 if n is not a krishnamurthy number + */ +int krishnamurthy(int n){ int sum=0; - if (get_digit(n,sum)==n){ - printf("%d is a krishnamurthy number\n",n); - } - else { - printf("%d is not a krishnamurthy number\n",n); - } + return get_digit(n,sum)==n; +} + +/** + * @brief Implementation of test cases + * @return void + */ +static void tests(){ + assert(krishnamurthy(1) == 1); + assert(krishnamurthy(13) == 0); + assert(krishnamurthy(45) == 0); + assert(krishnamurthy(145) == 1); + assert(krishnamurthy(239) == 0); + printf("All tests were successful!\n"); } int main(){ - int n = 13, x = 145; - printf("For example: \n"); - krishnamurthy(n); - krishnamurthy(x); + tests(); return 0; }