0

I've encountered a problem with a program I'm writing for school. I need to verify credit card numbers using the Luhn Algorithm, however I'm having some difficulty in getting the logic of the algorithm to work correctly. I believe I know where the problem is, but I'm unable to fix it.

I believe the problem is here:

For i = 0 To cardInput.Text.Length - 2 Step -2
    Dim x = (i * 2)
    If x > 9 Then
        x = x - 9
    End If
    oddTotal += x
Next

'Sum of undoubled digits
For i = 0 To cardLength - 1 Step -2
    evenTotal += i
Next

total = oddTotal + evenTotal

checkSum = total

infoOutput.Items.Add("CheckDigit: " & checkDigit)
infoOutput.Items.Add("CheckSum :" & checkSum)

'Verify that the card is valid by the Mod 10 (Lund algoritm)
If checkSum = checkDigit Or checkSum = 0 Then
    valid = True
Else
    valid = False
End If

If it's needed, the rest of my project can be seen here

My code doesn't seem to start at the last digit and take every other digit back to the beginning to be doubled. Is the Step -2 operator incorrect here? What am I doing wrong?

2
  • 1
    You do not appear to be using the digits of the card number. Commented Jul 19, 2015 at 17:38
  • I don't understand how I'm not though if I use this code to display the selected digit, it shows fine in my listbox. infoOutput.Items.Add(cardInput.Text.Substring(cardLength -2,1)) so my For loop should be selecting the digits and utilizing them correct? Commented Jul 19, 2015 at 17:46

1 Answer 1

2

There are several problems here. Particularly:

If you want a loop to count backwards, you have to start at the higher index and end at the lower one. So:

For i = cardInput.Text.Length - 2 To 0 Step -2

Then, instead of using i directly, you should use the i-ith digit:

Dim x = Val(cardInput.Text(i))

The same applies to your sum of evens.

If you want to check if the last digit is zero, use the Mod operator:

valid = (checkSum Mod 10 = 0)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! I didn't realize that stepping backwards the way I was wouldn't produce the same results as reversing the string in the input, and I forgot to put the Mod 10 back in when I was playing with various other items. +1 for the answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.