这是我的代码:
puts "Input a number."
Divisor = 2
inputNumber = gets.chomp
if inputNumber.to_i == 1 || inputNumber.to_i == 2
if inputNumber.to_i == 1
puts inputNumber + " is not a prime."
else
puts inputNumber + " is a prime."
end
else
while Divisor.to_i < inputNumber.to_i
if inputNumber.to_i%Divisor.to_i == 0
puts inputNumber + " is not a Prime as " + Divisor.to_s + " is a factor."
break
else
Divisor = Divisor.to_i + 1
end
end
puts inputNumber + " is a prime!"
end
我收到以下错误:
test1.rb:30: warning: already initialized constant Divisor
test1.rb:3: warning: previous definition of Divisor was here
有什么问题?
答案 0 :(得分:5)
Divisor
是常数。你想要一个变量:divisor
。请参阅此answer。
puts inputNumber + " is a prime!"
。break
替换为exit
,或使用布尔变量。.to_i
一次,进行计算,然后使用.to_s
显示结果(2..Math.sqrt(inputNumber))
inputNumber == 1
puts 'Input a number.'
divisor = 2
inputNumber = gets.chomp.to_i
prime = true
if inputNumber == 1
puts inputNumber.to_s + ' is not a prime.'
else
while divisor <= Math.sqrt(inputNumber)
if inputNumber % divisor == 0
puts inputNumber.to_s + ' is not a Prime as ' + divisor.to_s + ' is a factor.'
prime = false
break
else
divisor += 1
end
end
puts inputNumber.to_s + ' is a prime!' if prime
end
可以使用Enumerable#find
编写更短的替代方案。它使用每个元素执行块,一旦块中的代码返回truthy值就停止,并返回块为真的元素。如果未找到任何元素,则返回nil
:
puts 'Input a number.'
number = gets.chomp.to_i
divisor = (2..Math.sqrt(number)).find { |i| number % i == 0 }
if number == 1
puts '1 is not a prime.'
elsif divisor
puts format('%d is not a prime as %d is a factor.', number, divisor)
else
puts format('%d is a prime!', number)
end