Advertisement
uriid1

Sum 2 big int | LUA

Sep 9th, 2023 (edited)
1,344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.19 KB | None | 0 0
  1. --[[
  2.     ####--------------------------------####
  3.     #--# Author:   by uriid1            #--#
  4.     #--# License:  GNU GPLv3            #--#
  5.     ####--------------------------------####
  6. --]]
  7.  
  8. local ASCII_ZERO_CODE = 48
  9. local ASCII_NINE_CODE = 57
  10.  
  11. io.stdout:write('First number: ')
  12. local a_str = io.stdin:read()
  13. io.stdout:write('Second number: ')
  14. local b_str = io.stdin:read()
  15.  
  16. local function stringToNumArr(str)
  17.   local result = {}
  18.   for s in string.gmatch(str, '.') do
  19.     local code = string.byte(s)
  20.     if code < ASCII_ZERO_CODE or code > ASCII_NINE_CODE then
  21.       return nil, 'Out of ascii range'
  22.     end
  23.     table.insert(result, code - ASCII_ZERO_CODE)
  24.   end
  25.   return result
  26. end
  27.  
  28. local a, err = stringToNumArr(a_str)
  29. if err then
  30.   print(err)
  31.   return
  32. end
  33.  
  34. local b, err = stringToNumArr(b_str)
  35. if err then
  36.   print(err)
  37.   return
  38. end
  39.  
  40. local c = {}
  41. local x = 0
  42.  
  43. for i = #a, 1, -1 do
  44.   local sum = a[i] + x + (b[i-1] or 0)
  45.   if sum > 9 then
  46.     x = math.floor(sum / 10)
  47.     table.insert(c, sum - 10)
  48.   else
  49.     table.insert(c, sum)
  50.   end
  51. end
  52.  
  53. local result = {}
  54. for i = #c, 1, -1 do
  55.   table.insert(result, c[i])
  56. end
  57. print('result:', table.concat(result))
Tags: lua
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement