Skip to content

Commit

Permalink
Merge pull request iluwatar#112 from soer-robin/master
Browse files Browse the repository at this point in the history
Add Luhn Algorithm.
  • Loading branch information
iluwatar authored Oct 30, 2021
2 parents cb86cde + 7147e8b commit abb70cb
Show file tree
Hide file tree
Showing 4 changed files with 183 additions and 0 deletions.
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Inspired by [30 seconds of code](https://github.com/Chalarangelo/30-seconds-of-c
[![Fibonacci](https://img.shields.io/badge/-Fibonacci-e1b050)](#fibonacci) [![link](https://img.shields.io/badge/-Repository%20link-969c56?logo=github)](https://github.com/iluwatar/30-seconds-of-java/blob/master/src/main/java/math/FibonacciSnippet.java)
[![Haversine Formula](https://img.shields.io/badge/-Haversine%20formula-e1b050)](#haversine-formula) [![link](https://img.shields.io/badge/-Repository%20link-969c56?logo=github)](https://github.com/iluwatar/30-seconds-of-java/blob/master/src/main/java/math/HaversineFormulaSnippet.java)
[![Lottery](https://img.shields.io/badge/-Lottery-e1b050)](#lottery) [![link](https://img.shields.io/badge/-Repository%20link-969c56?logo=github)](https://github.com/iluwatar/30-seconds-of-java/blob/master/src/main/java/math/PerformLotterySnippet.java)
[![Luhn algorithm](https://img.shields.io/badge/-Luhn%20algorithm-e1b050)](#Luhn algorithm) [![link](https://img.shields.io/badge/-Repository%20link-969c56?logo=github)](https://github.com/iluwatar/30-seconds-of-java/blob/master/src/main/java/math/LuhnSnippet.java)
[![Greatest Common Divisor](https://img.shields.io/badge/-Greatest%20Common%20Divisor-e1b050)](#greatest-common-divisor) [![link](https://img.shields.io/badge/-Repository%20link-969c56?logo=github)](https://github.com/iluwatar/30-seconds-of-java/blob/master/src/main/java/math/GreatestCommonDivisorSnippet.java)
[![Prime](https://img.shields.io/badge/-Prime-e1b050)](#prime) [![link](https://img.shields.io/badge/-Repository%20link-969c56?logo=github)](https://github.com/iluwatar/30-seconds-of-java/blob/master/src/main/java/math/PrimeNumberSnippet.java)
[![Natural Number Binary Conversion](https://img.shields.io/badge/-Natural%20Number%20Binary%20Conversion-e1b050)](#natural-number-binary-conversion) [![link](https://img.shields.io/badge/-Repository%20link-969c56?logo=github)](https://github.com/iluwatar/30-seconds-of-java/blob/master/src/main/java/math/NaturalNumberBinaryConversionSnippet.java)
Expand Down Expand Up @@ -478,6 +479,33 @@ Inspired by [30 seconds of code](https://github.com/Chalarangelo/30-seconds-of-c
}
```

### Luhn algorithm
```java
public static int calculateLuhnChecksum(long num) {
if (num < 0) {
throw new IllegalArgumentException("Non-negative numbers only.");
}
final var numStr = String.valueOf(num);

var sum = 0;
var isOddPosition = true;
// We loop on digits in numStr from right to left.
for (var i = numStr.length() - 1; i >= 0; i--) {
final var digit = Integer.parseInt(Character.toString(numStr.charAt(i)));
final var substituteDigit = (isOddPosition ? 2 : 1) * digit;

final var tensPlaceDigit = substituteDigit / 10;
final var onesPlaceDigit = substituteDigit % 10;
sum += tensPlaceDigit + onesPlaceDigit;

isOddPosition = !isOddPosition;
}
final var checksumDigit = (10 - (sum % 10)) % 10;
// Outermost modulus handles edge case `num = 0`.
return checksumDigit;
}
```

### Greatest Common Divisor

```java
Expand Down
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ dependencies {
// 'test.useTestNG()' to your build script.
testImplementation 'org.hamcrest:hamcrest-library:1.3'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.2'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.6.2'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.2'
}

Expand Down
64 changes: 64 additions & 0 deletions src/main/java/math/LuhnSnippet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* MIT License
*
* Copyright (c) 2017-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package math;

public class LuhnSnippet {

/**
* Calculates checksum for a given number with Luhn's algorithm. Works only on non-negative
* integers not greater than {@link Long#MAX_VALUE} i.e., all numbers with a maximum of 18
* digits, plus 19-digit-long numbers start with 1..8 (also some with 9, too). For
* demonstration purposes, algorithm is not optimized for efficiency.
*
* @param num number whose checksum is to be calculated
* @return checksum value for num
* @see <a href="https://patents.google.com/patent/US2950048A">Hans P. LUHN's patent US2950048A</a>
* @see <a href="https://en.wikipedia.org/wiki/Luhn_algorithm">Luhn algorithm on Wikipedia</a>
*/
public static int calculateLuhnChecksum(long num) {
if (num < 0) {
throw new IllegalArgumentException("Non-negative numbers only.");
}
final var numStr = String.valueOf(num);

var sum = 0;
var isOddPosition = true;
// Loop on digits of numStr from right to left.
for (var i = numStr.length() - 1; i >= 0; i--) {
final var digit = Integer.parseInt(Character.toString(numStr.charAt(i)));
final var substituteDigit = (isOddPosition ? 2 : 1) * digit;

final var tensPlaceDigit = substituteDigit / 10;
final var onesPlaceDigit = substituteDigit % 10;
sum += tensPlaceDigit + onesPlaceDigit;

isOddPosition = !isOddPosition;
}
final var checksumDigit = (10 - (sum % 10)) % 10;
// Outermost modulus handles edge case `num = 0`.
return checksumDigit;
}

}
90 changes: 90 additions & 0 deletions src/test/java/math/LuhnSnippetTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* MIT License
*
* Copyright (c) 2017-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package math;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class LuhnSnippetTest {

@CsvSource({
"0, 0",
"1, 8",
"4, 2",
"5, 9",
"9, 1",

"42, 2",

// Moderately interesting patterns.
"10, 9",
"11, 7",
"12, 5",
"100, 8",
"101, 6",
"102, 4",
"1000, 9",
"1001, 7",
"1002, 5",
"10000, 8",
"10001, 6",
"10002, 4", // etc.

// Can detect any single-digit error.
"4872148, 4", // Original number (Luhn's example in patent US2950048A).
"4872143, 5",
// ^
"4872178, 1",
// ^

// Can detect many transposition of adjacent digits.
"4872418, 1",
// ^^
"4872184, 9",
// ^^

// Can not detect some transposition of adjacent digits.
"109223344, 2", // Original number.
"190223344, 2", // 09<-->90
//^^
"109553344, 2", // 22<-->55
// ^^
"109226644, 2", // 33<-->66
// ^^
"109223377, 2", // 44<-->77
// ^^
"190226644, 2", // Some of the above together.
//^^ ^^
"190556677, 2", // All of the above together.
//^^^^^^^^
})
@ParameterizedTest
void testLuhnCalculateChecksum(long num, int expectedChecksum) {
assertEquals(expectedChecksum, LuhnSnippet.calculateLuhnChecksum(num));
}

}

0 comments on commit abb70cb

Please sign in to comment.