#!/usr/bin/ruby

#
## http://rosettacode.org/wiki/Long_multiplication
#

func add_with_carry(result, addend, addendpos) {
    while (true) {
        while (result.len < addendpos+1) {
            result.append(0);
        }
        var addend_digits = (addend.to_i + result[addendpos].to_i -> digits.reverse);
        result[addendpos] = addend_digits.pop;
        addend_digits.len > 0 || break;
        addend = addend_digits.pop;
        addendpos++;
    }
}
 
func longhand_multiplication(multiplicand, multiplier) {
 
    var result = [];
    var multiplicand_offset = 0;
 
    multiplicand.reverse.each { |multiplicand_digit|
        var multiplier_offset = multiplicand_offset;
        multiplier.reverse.each { |multiplier_digit|
            var multiplication_result = (multiplicand_digit.to_i * multiplier_digit.to_i -> to_s);
 
            var addend_offset = multiplier_offset;
            multiplication_result.reverse.each { |result_digit_addend|
                add_with_carry(result, result_digit_addend, addend_offset);
                addend_offset++;
            };
            multiplier_offset++;
        };
        multiplicand_offset++;
    };
 
    return result.join.reverse;
}
 
say longhand_multiplication('18446744073709551616', '18446744073709551616');
