这是我的代码:
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
怎么了?
Divisor
是一个常数.你想要一个变量:divisor
.看到这个答案.
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