From the book Think Like a Programmer (emphasis mine)

The Luhn formula is a widely used system for validating identification numbers. Using the original number, double the value of every other digit. Then add the values of the individual digits together (if a doubled value now has two digits, add the digits individually). The identification number is valid if the sum is divisible by 10. Write a program that takes an identification number of arbitrary length and determines whether the number is valid under the Luhn formula. The program must process each character before reading the next one.

In a broader sense, what does it mean to process each character before reading the next one? What does this look like syntactically? What does the opposite mean and what does it look like syntactically?


For some background, here's my attempt at the problem (in JavaScript):

Array.prototype.sum = function() {
    var sum = 0,
        itemCount = this.length,

    for(i = 0; i <= itemCount - 1; i++) {
        sum += this[i];

    return sum;

function validateNumberWithLuhnForumla(number) {
    var numbersArray = number.toString().split(''),
        numberCount = numbersArray.length,
        i = 0,
        isValid = false,
        numbersToSum = [];

    for(i = 0; i <= numberCount - 1; i++) {
        if(i % 2 > 0 && i > 0) {
            doubledDigit = numbersArray[i] * 2;
            if(doubledDigit > 9) {
                numbersToSum.push(1, (doubledDigit - 10));
            } else {

    checkSum = numbersToSum.sum();

    if(checkSum % 10 === 0) {
        isValid = true;

    return isValid;
  • 2
    foreach(c in input)state=calcSomething(state, c); May 18, 2013 at 19:34

2 Answers 2


It means that you're allowed to retain the value of one character in memory only until the next input operation happens. This is an idealization of the common practical constraint that an algorithm must be able to process arbitrary input without requiring arbitrary amounts of RAM. A simple practical test is: does your solution work with only a single char variable?


The opposite would be for example reading the whole identification number into a string, and then making multiple passes over the digits of the identification number to calculate the Luhn checksum. The question is asking you to calculate the checksum without looking back to previous digits.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.