forked from piyush-kash/Hacktober2021-cpp-py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathluhn_algo.cpp
More file actions
38 lines (31 loc) · 704 Bytes
/
luhn_algo.cpp
File metadata and controls
38 lines (31 loc) · 704 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// C++ program to implement Luhn algorithm
#include <bits/stdc++.h>
using namespace std;
// Returns true if given card number is valid
bool checkLuhn(const string& cardNo)
{
int nDigits = cardNo.length();
int nSum = 0, isSecond = false;
for (int i = nDigits - 1; i >= 0; i--) {
int d = cardNo[i] - '0';
if (isSecond == true)
d = d * 2;
// We add two digits to handle
// cases that make two digits after
// doubling
nSum += d / 10;
nSum += d % 10;
isSecond = !isSecond;
}
return (nSum % 10 == 0);
}
// Driver code
int main()
{
string cardNo = "79927398713";
if (checkLuhn(cardNo))
printf("This is a valid card");
else
printf("This is not a valid card");
return 0;
}