请帮我解决这个ruby总和

  • 本文关键字:ruby 总和 解决 ruby
  • 更新时间 :
  • 英文 :


你已经得到3个整数- N1, N2和N3。找出N1和N2之间有多少个数(包括N1和N2)能被N3整除。打印这些数字并计数。如何找到它

输入

N1 = 1
N2 = 100
N3 = 3

让我们现在创建数组

a = [*N1..N2]
#=>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]

代码
result = a.select { |x| x % 3 == 0 }

result = a.filter { |x| x.divmod(N3).last.zero? }
p result
p result.count

输出
#=>[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
#=>33

相关内容

  • 没有找到相关文章

最新更新