0

Luhn algorithm

Used to verify credit card numbers

  1. 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).
  2. Take the sum of all the digits.
  3. 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?

overexchange
  • 15,768
  • 30
  • 152
  • 347
  • 1
    In general, the implementation of an algorithm (as horrible as it may be) does not change the complexity of the algorithm. For the Luhn algorithm, the complexity is O(n) where `n` is the number of digits. As for the space complexity, using recursion does waste stack space, so this implementation has O(n) wasted space. – user3386109 Nov 28 '16 at 00:07
  • Note that this code leaks memory horribly; you allocate tuples all over the place, but never free any of them. – Jonathan Leffler Nov 28 '16 at 02:20

0 Answers0