ruby完成一道百度的测试题目
题目:
第一题:连续正整数
题目描述:一个正整数有可能可以被表示为n(n>=2)个连续正整数之和,如:
15=1+2+3+4+5
15=4+5+6
15=7+8
请编写程序,根据输入的任何一个正整数,找出符合这种要求的所有连续正整数序列。
输入数据:一个正整数,以命令行参数的形式提供给程序。
puts "Input the integer:"number = getsint_number = Integer(number)hasResult = false;(1..int_number/2).each do |number_low| ((number_low+1)..int_number).each do |number_high| #The equation is (a+b)*(b-a+1)/2 数列求和公式 result = (number_low+number_high) * (number_high-number_low+1) / 2 if(result == int_number) puts (number_low..number_high).to_a.inspect hasResult = true; break; elsif(result > int_number) break end endendif(!hasResult) puts "NONE"end
puts "Input the integer:"number = getsdef sub_seq(int_number) seqs = Array.new; (1..int_number/2).each do |number_low| ((number_low+1)..int_number).each do |number_high| result = (number_low+number_high) * (number_high-number_low+1) / 2 if(result == int_number) #The equation is (a+b)*(b-a+1)/2 seqs << (number_low..number_high) break; elsif(result > int_number) #this can reduce some loops break end end end seqsendsub_seq(Integer(number)).each do |ran| puts ran.to_a.inspectend