1

I am trying to make this program to factor a number work in lua, and everything works except for this one line of code in it. Here's the code:

function factor(a)
 print("factoring: " .. a)
 print()
 totali = 0
 totaldiv = 0
 for i = 1, a do
  if (a%i == 0) then
   if (i<a) then
    totaldiv = totaldiv + 1
   end
   print(i)
   i = i + 1
   totali = totali + 1
  else
   i = i + 1
  end
 end
 if totali == 2 then
  print("That is a prime number!")
 elseif totaldiv == a then
  print("That is a perfect number!")
 end
end
io.write("Enter a number to factor: ")
some = io.read()
factor(some)
io.read()

The offensive line is if (i<a) then from what I've seen. What am I doing wrong? Thanks!

7
  • The value you get back from io.read will be a string, yes. You need to convert it to a number if you want that (lua will do that implicitly in some cases too). Commented Jul 8, 2015 at 18:22
  • @Etan Reisner, How do I make the number the variable a? If it was, wouldn't it output 6 as a perfect number, or am I wrong in another part of it? It seems to me it's not making a the actual function argument. I did "i<tonumber(a)" EDIT: I changed it to totaldiv = totaldiv + i, but still no luck. Commented Jul 8, 2015 at 18:27
  • I have no idea what problem you are actually having. Your post was cut off and you didn't say what the problem was. I just gave a generic answer about io.read and string values. Fix your post, clearly explain the exact problem and I might be able to help more. Commented Jul 8, 2015 at 18:31
  • Ok... It cut off my post for some reason. I'm trying to get my program to output "That is a perfect number!" If the sum of its proper divisors is equal to the number itself. From what I'm seeing, it's not even doing anything with that part. I tried printing totaldiv after the for loop right before the second to last end, and it doesn't even print anything... I suck at this. OK I converted the last a to a number and it worked! Thanks! Commented Jul 8, 2015 at 18:34
  • 2
    Replace factor(some) with factor(some + 0) or factor(tonumber(some)) Commented Jul 9, 2015 at 10:18

1 Answer 1

1

if (i<tonumber(a)) then should work.
You requested an input, which will be returned as a string.
Therefore, you can't do if (i<a) then, because you're comparing number and string via <.
You simply can't say, that 2 is less than '4'

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, sorry... I was probably tired, when writing this. It's fixed now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.