How to resolve the algorithm Luhn test of credit card numbers step by step in the Bash 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 Bash 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 Bash programming language

Source code in the bash programming language

#!/bin/bash

function luhn_validate  # <numeric-string>
{
    num=$1
    shift 1

    len=${#num}
    is_odd=1
    sum=0
    for((t = len - 1; t >= 0; --t)) {
        digit=${num:$t:1}

        if [[ $is_odd -eq 1 ]]; then
            sum=$(( sum + $digit ))
        else
            sum=$(( $sum + ( $digit != 9 ? ( ( 2 * $digit ) % 9 ) : 9 ) ))
        fi

        is_odd=$(( ! $is_odd ))
    }

    # NOTE: returning exit status of 0 on success
    return $(( 0 != ( $sum % 10 ) ))
}


function print_result  # <numeric-string>
{
    if luhn_validate "$1"; then
        echo "$1 is valid"
    else
        echo "$1 is not valid"
    fi
}

print_result "49927398716"
print_result "49927398717"
print_result "1234567812345678"
print_result "1234567812345670"


  

You may also check:How to resolve the algorithm Array concatenation step by step in the bash programming language
You may also check:How to resolve the algorithm Tic-tac-toe step by step in the Bash programming language
You may also check:How to resolve the algorithm Array length step by step in the Bash programming language
You may also check:How to resolve the algorithm FizzBuzz step by step in the bash programming language
You may also check:How to resolve the algorithm Bitmap/Bresenham's line algorithm step by step in the bash programming language