Task

Explicitly implement   long multiplication.

This is one possible approach to arbitrary-precision integer algebra.



For output, display the result of    264 * 264.

Optionally, verify your result against builtin arbitrary precision support.

The decimal representation of    264    is:

18,446,744,073,709,551,616

The output of    264 * 264    is    2128,    and is:

340,282,366,920,938,463,463,374,607,431,768,211,456



/* NetRexx */
options replace format comments java crossref symbols nobinary
 
numeric digits 100
 
runSample(arg)
return
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method multiply(multiplier, multiplicand) public static
  result = ''
  mpa = s2a(multiplier)
  mpb = s2a(multiplicand)
  r_ = 0
  rim = 1
  loop bi = 1 to mpb[0]
    loop ai = 1 to mpa[0]
      ri = ai + bi -1
      p_ = mpa[ai] * mpb[bi]
      loop i_ = ri by 1 until p_ = 0
        s_ = r_[i_] + p_
        r_[i_] = s_ // 10
        p_ = s_ % 10
        end i_
      rim = rim.max(i_)
      end ai
    end bi
  r_[0] = rim
  result = a2s(r_)
  result = result.strip('l', 0)
  if result = '' then result = 0
  return result
 
-- .............................................................................
-- copy characters of a numeric string into a corresponding array
-- digits are numbered 1 to n from right to left
method s2a(numbr) private static
  result = 0
  lstr = numbr.length()
  loop z_ = 1 to lstr
    result[z_] = numbr.substr(lstr - z_ + 1, 1)
    end z_
  result[0] = lstr
  return result
 
-- .............................................................................
-- turn the array of digits into a numeric string
method a2s(numbr) private static
  result = ''
  loop z_ = numbr[0] to 1 by -1
    result = result || numbr[z_]
    end z_
  return result
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  mms = [ -
                      123',  '123, -
                      012',  '12, -
             123456789012' , '44444444444, -
                  2 ** 64' , '2**64, -
                        0'                      ,0 ' -
  ]
  ok = 0
  errors = 0
 
  loop mm over mms
    parse mm multiplier . ',' multiplicand .
    builtIn = multiplier * multiplicand
    calculated = multiply(multiplier, multiplicand)
    say 'Calculate' multiplier + 0 'x' multiplicand + 0
    say 'Built in:' builtIn
    say 'Derived: ' calculated
    say
    if builtIn = calculated then ok = ok + 1
    else                         errors = errors + 1
    end mm
  say ok 'ok'
  say errors 'not ok'
 
  return
 