Skip to content

Commit

Permalink
Added test cases in krishnamurthy.c
Browse files Browse the repository at this point in the history
  • Loading branch information
jspmic committed Dec 1, 2023
1 parent be91dd7 commit b7152a0
Showing 1 changed file with 44 additions and 22 deletions.
66 changes: 44 additions & 22 deletions math/krishnamurthy.c
Original file line number Diff line number Diff line change
@@ -1,29 +1,39 @@
#include <stdio.h>
#include <stdio.h> // For I/O ops
#include <assert.h> //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);
Expand All @@ -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;
}

0 comments on commit b7152a0

Please sign in to comment.