Task 156 - Luhn Algorithm

Back to General discussions forum

Maximization     2014-12-04 15:34:06

What do you do with cases such as 81?6607602876038 that have an intermediate checksum of an odd number (61 in this example) and need to be replaced by a number on which the position is an even index (14 here)?

To have a checksum of a multiple of 10 I'd have to replace '?' with (70 - 61) / 2 = 9 / 2 = 3.5, but that's obiously impossible. Am I missing something here?

Rodion (admin)     2014-12-04 17:25:04
User avatar

> with (70 - 61) / 2 = 9 / 2 = 3.5

But I'm afraid it is not exactly correct to simply divide by 2!

It would be only true if the digit, when doubled, is less than 10.

So you need to either figure out some enhancement for your forumla, or simply loop through all possible digits and check for which of them the checksum is correct :)

Maximization     2014-12-04 18:38:50

Ahh of course, thank you. Your hint to loop through all possible digits made my solution much less verbose. It seems I have to start to get out of main and think in a more OO oriented now that problems increase in difficulty, it makes more sense in Java at least.

There's another thing though. All my answers were correct except this case: http://i.imgur.com/kjMLVv9.jpg

The input number was 1908348648908477 and altough this checksums to 90, the proposed solution swaps the most left 9 with it's neighbouring 0. The resulting 1098348648908477 checksums to 90 as well so it's technically correct, but if the input number is already a valid account shouldn't it be leaved as it is?

Rodion (admin)     2014-12-04 19:01:55
User avatar

I think you are right and this looks bit silly, but problem statement says for simplicity that all card numbers present in the input are incorrect for sure, so that something should be fixed.

Though perhaps it would be better to disable such cases (with swapping adjacent 0 and 9) completely to prevent such "silly" cases. I'll try to take care of this, thank you!

> Your hint to loop through all possible digits

I think you still can fix the formula - if you get odd value which should be divided by two, you need to increment it by 9 befor dividing (or by 4.5 after). Just an idea...

Maximization     2014-12-05 11:50:35

The problem statement does say that all the numbers are incorrect so then at least one digit swap should be made. Having focused so much on the solution I forgot about that initial sentence. I fixed it now and managed to solve the problem. Thanks for your help!

Marchel Sugi     2015-07-08 00:59:02
User avatar

About to ask the '0' and '9' before stumble into this... thanks.

Stefan Dell     2015-07-12 14:35:49

Can you explain why in some numbers thow the luhn algorithm is correct , and the unknown number that i found is also correct , your answer changes some digits and makes answer wrong? thanks.

Please login and solve 5 problems to be able to post at forum