How to resolve the algorithm Luhn test of credit card numbers step by step in the Swift programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Luhn test of credit card numbers step by step in the Swift programming language
Table of Contents
Problem Statement
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
For example, if the trial number is 49927398716:
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and use it to validate the following numbers:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Luhn test of credit card numbers step by step in the Swift programming language
Source code in the swift programming language
func luhn(_ number: String) -> Bool {
return number.reversed().enumerated().map({
let digit = Int(String($0.element))!
let even = $0.offset % 2 == 0
return even ? digit : digit == 9 ? 9 : digit * 2 % 9
}).reduce(0, +) % 10 == 0
}
luhn("49927398716") // true
luhn("49927398717") // false
You may also check:How to resolve the algorithm FizzBuzz step by step in the VBScript programming language
You may also check:How to resolve the algorithm Loops/Wrong ranges step by step in the Arturo programming language
You may also check:How to resolve the algorithm Multifactorial step by step in the Haskell programming language
You may also check:How to resolve the algorithm Self numbers step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Comma quibbling step by step in the Common Lisp programming language