I'm working through the problems in Project Euler and I ran into an issue with Problem 16. I'm trying to turn 21000 into a string so that I can iterate over its digits and add them up. It seemed simple enough. I started with this code:
local powerDigits = tostring(2^1000)
local sum = 0
for c in string.gmatch(powerDigits, ".") do
sum = sum + tonumber(c)
end
print(sum)
Result: error. The number that I was iterating over was not the full number in standard form, but rather 1.0715086071863e+301, and you can't add "." to 1. So I went in search of some assistance.
I first found a little library called bignum-lua that said it could handle big numbers. I tried it like so:
local bignum = require "bignum"
local base = bignum(2)
local powerBase = bignum.pow(base, 1000)
local powerDigits = tostring(powerBase)
local sum = 0
for c in string.gmatch(powerDigits, ".") do
sum = sum + tonumber(c)
end
print(sum)
Result: same error. The big number was still being printed in scientific notation.
I then found lua-bignumber and tried it, but it failed at the start. The library threw errors because of its starting code:
local class = require 'ext.class'
local table = require 'ext.table'
local range = require 'ext.range'
local number = require 'ext.number'
local math = require 'ext.math'
local assert = require 'ext.assert'
"ext.class" is undefined, as are some of the others. The library was referencing things I don't have.
I went looking again and found CC-Big-Numbers, but I couldn't figure out how to include that one in my code. I got errors because of what I thought I was supposed to include at the very start:
local prop_BigNumbers = script:GetCustomProperty("_BigNumbers")
bn = require(prop_BigNumbers)
Lua couldn't figure out what "script" meant in this context, and neither can I.
So now, I come to you for help. What can I do to take an enormous number, compute its exact value, and iterate over all of its digits to add them up? Thank you in advance.
EDIT: Solved! Thanks to u/particlemanwavegirl for the hint. If any of you are working on Project Euler, look away now to avoid spoilers, but here's what I did this time:
local powerDigits = 2^1000
local sum = 0
while powerDigits > 0 do
local lastDigit = powerDigits % 10
sum = sum + lastDigit
powerDigits = (powerDigits - lastDigit) / 10
end
print(sum)
Thanks again to this community!