Sum of prime numbers in a number - Lua

I am trying to calculate the sum of prime numbers in a given number. For example, for the number 123456, the result will be 10, because 2 + 3 + 5 = 10.

I tried to write code that does this in Lua, but I had some problems.

First, here's the code:

    function isPrime(num)
if(num == 1 or (num ~= 2 and num%2 == 0)) then
  return false
end
for i=3, math.sqrt(num), 2 do
  if(num%i == 0) then
    return false
  end
end
return true
end

function sumOfPrimes(num)
local sum = 0
for digit in string.gmatch(num,"%d") do
  local prime = isPrime(digit)
  if(isPrime(digit)) then
    sum = sum + digit
  end
  print(digit)
end
return sum
end

function main()
print(sumOfPrimes(123456))
end
main()

      

It returns 9 instead of 10. Another thing I noticed is adding 1 to the sum as well, but 1 is not simple. What is the problem?

+3


source to share


1 answer


string.gmatch returns a string, you need to convert it to a number before doing calculations

Btw, you are doing the first check twice in your loop.

This is the fixed version (returns 10 as expected):



...

function sumOfPrimes(num)
    local sum = 0
    for digit in string.gmatch(num, "%d") do
        digit = tonumber(digit) --needed conversion
        local prime_digit = isPrime(digit)
        if prime_digit then
            sum = sum + digit
        end
    end
    return sum
end

      

+6


source







All Articles