我需要编写一些可以识别强数的代码。
强数是指数字的阶乘之和等于数字本身的数字。
例如:145,因为1! + 4! + 5! = 1 + 24 + 120 = 145
我一直在试图解决这个问题,但无济于事。谁能告诉我我要去哪里错了?我需要在每个循环中增加“ adder”和“ multiplier”变量,因此我可以在方法末尾比较总数,但它们始终默认为零。谁能看到我要去哪里错了?谢谢!
def strong_num(n)
digits=n.divmod(1)
multiplier=1
adder=0
digits.each do |digit|
x=digit
digit-1.times do
multiplier=multiplier*x
adder=adder+multiplier
x=x-1
end
end
if n==adder
return "STRONG!!!!"
else
return "Not Strong !!"
end
end
样本输入:
Test.assert_equals(strong_num(1) , "STRONG!!!!")
Test.assert_equals(strong_num(2) , "STRONG!!!!")
Test.assert_equals(strong_num(7) , "Not Strong !!")
Test.assert_equals(strong_num(93) , "Not Strong !!")
Test.assert_equals(strong_num(145), "STRONG!!!!")
Test.assert_equals(strong_num(185), "Not Strong !!")
示例输出:
Test Passed: Value == "STRONG!!!!"
Test Passed: Value == "STRONG!!!!"
Expected: "Not Strong !!", instead got: "STRONG!!!!"
Expected: "Not Strong !!", instead got: "STRONG!!!!"
Test Passed: Value == "STRONG!!!!"
Expected: "Not Strong !!", instead got: "STRONG!!!!"
Test Passed: Value == "STRONG!!!!"
Expected: "Not Strong !!", instead got: "STRONG!!!!"
答案 0 :(得分:0)
希望这会有所帮助! 我试图通过将代码分成几部分来减少代码
输入:145
def method_name(num)
array = num.to_s.chars.map(&:to_i) # => [1,4,5]
fact_arr = array.map {|f| fact(f)} # => [1, 24, 120]
if (num == fact_arr.inject(:+))
return "STRONG!!"
else
return "NOT STRONG!!"
end
end
def fact(n)
if (n == 0)
1
else
n * fact(n-1)
end
end
答案 1 :(得分:0)
k.divmod(n)
返回一个数组= [quocient_of_division(k / n),除法其余部分(k / n)]。示例:145.divmod(1)
返回=>[145, 0]
。另外,您代码中的digit-1.times
应该是(digit-1).times
我认为可以做到的方式是这样的:
def is_strong?(number)
result = 0
numbers = number.to_s.chars.map(&:to_i)
powers = { 0 => 1, 1 => 1, 2 => 2, 3 => 6, 4 => 24, 5 => 120, 6 => 760, 7 => 5040, 8 => 40320, 9 => 362880 }
numbers.each do |n|
result += powers[n]
end
return (result == number)
end