Search code examples
javaluhn

New to Java, having trouble making a Luhn algorithm


The prompt requires me to have the public static below and to only use recursion. This is my first week using Java so my knowledge base is pretty low. I saw some code online for the Luhn algorithm but none of it seemed to use a Boolean as a second parameter.

Basically I need to create a Luhn Algorithm, where it takes each value (right to left), doubles the second value (the Boolean is used to determin if the number will be doubled or not) and then adds all the values together. For ex). System.out.println(sumLuhnDigits(7992739871005L, false));

Would return 72

The problem I'm running into, regards the 'long' type.

Java is telling me I need to initiate the count variable before setting it equal to (number%10).. etc. I assume that's because I have it set as += and it needs to have value in order to do so. Setting it equal to 0 at the top however, messes with the counter I was trying to make.

The syntax also doesn't like when I try to return count either, saying it's not a 'long' type. It seems I'm currently stuck in a stackoverflow error as well. So I need to break out of the recursion.

public static long sumLuhnDigits(long number, boolean odd) {
    /// Java IDE said I needed to initiate the variable count but now it won't accumulate properly being set = 0
    long count = 0;

    if (odd == false) {

        count += number % 10;
        number = number / 10;

        odd = true;
        return sumLuhnDigits(number, odd);

    } if (odd == true) {
        count += (number % 10) * 2;
        number = number / 10;
        odd = false;
        return sumLuhnDigits(number, odd);

        /// Here I ran into the problem that count is not the type long, this is also as far as I have gotten     
    } if (number == 0) {
        return count;
    }
}

Solution

    1. Count is definitely a long type

    2. You're not accumulating anything because you are recursing and resetting a local variable.

    You could try two methods to pass along the count (there's other ways to do the same thing). Also, I doubt a card number will add up to more than an integer maximum.

    public static int sumLuhnDigits(long number, boolean odd) {
        return sumLuhnDigits(number, odd, 0);
    } 
    
    private static int sumLuhnDigits(long number, boolean odd, int count) {
       if (number <= 0) return count;
       if (!odd) {
           count += number % 10;
       } else {
           count += (number % 10) * 2;
      } 
      number = number / 10;
      odd = !odd;
      return sumLuhnDigits(number, odd, count);
    }