Skip to content

Instantly share code, notes, and snippets.

@mfukar
Last active Nov 8, 2021
Embed
What would you like to do?
The Luhn test in C++11
#include <algorithm>
#include <numeric>
#include <iostream>
#include <vector>
/*
* Assuming an input of a string of digits, perform the Luhn test on the indicated sequence.
* Returns true if the given string passes the test, false otherwise.
*/
bool luhn(const std::string& seq) {
static const int m[] = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };
bool is_odd = false;
auto lambda = [&](int a, char c) {
return a + ((is_odd = !is_odd) ? c - '0' : m[c - '0']);
};
int sum = std::accumulate(seq.rbegin(), seq.rend(), 0, lambda);
return 0 == sum % 10;
}
int main (void) {
auto t_cases = {"49927398716", "49927398717", "1234567812345678", "1234567812345670"};
auto print = [](const std::string & s) { std::cout << s << ": " << luhn (s) << std::endl; };
std::for_each (t_cases.begin (), t_cases.end (), print);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment