Luhn algorithm
Used to verify credit card numbers
- From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then sum the digits of the products (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or alternatively subtract 9 from the product (e.g., 16: 16 - 9 = 7, 18: 18 - 9 = 9).
- Take the sum of all the digits.
- If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.
Implementation
#include<stdlib.h>
#include<stdio.h>
#include<stddef.h>
int luhnSum(int);
typedef struct{
int quotient;
int remainder;
}Tuple;
Tuple* split(int number){
/* Split positive number into all but its last digit and its last digit */
Tuple *tuple = malloc(sizeof(Tuple));
tuple->quotient = number / 10;
tuple->remainder = number % 10;
return tuple;
}
int sumDigits(int number){
/* Return the sum of digits of positive number n */
Tuple *tuple = NULL;
if(number < 10){
return number;
}else{
tuple = split(number);
return sumDigits(tuple->quotient) + tuple->remainder;
}
}
int luhnSumDouble(int number){
Tuple *tuple = split(number);
int luhnDigit = sumDigits(2*(tuple->remainder));
if(number < 10){
return luhnDigit;
}else{
return luhnSum(tuple->quotient + luhnDigit);
}
}
int luhnSum(int number){
Tuple *tuple = NULL;
if(number < 10){
return number;
}else{
tuple = split(number);
return luhnSumDouble(tuple->quotient) + tuple->remainder;
}
}
int main(void){
}
How to analyse the space & time complexity of mutual recursion code?