我已经找了两个多小时的问题,正确的答案是4179871,但我只得到了4177763,
完全数是指它的适当除数之和与其数完全相等的一个数。例如,28的适当除数之和为1+2+4+7+ 14 = 28,这意味着28是一个完美数。 如果一个数n的适当除数之和小于n,则称为亏,如果这个数大于n,则称它为富足数。 由于12是最小的富足数,1+2+3+4+6= 16,可以写成两个富足数之和的最小数是24。通过数学分析,可以证明所有大于28123的整数都可以写成两个丰富数的和。然而,这个上限不能通过分析进一步降低,即使已知不能表示为两个丰富数之和的最大数小于这个极限。 找出所有正整数的和,这些正整数不能写成两个丰富数的和。
def factors(num) # function that returns array of factors
factorsNums = []
for i in 1..Math.sqrt(num).ceil
if num % i == 0
factorsNums.push(i) if i != num
factorsNums.push(num / i) if ((num / i) < num) && ((factorsNums.include? (num / i)) == false)
end
end
factorsNums
end
abundantNumbers = []
for i in 1..28123 #This loop will push into the array "abundantNumbers" each number from 1 to 28123 that is an abundant number (a number in which the sum of its divisors is bigger than the number itself)
abundantNumbers.push(i) if factors(i).inject(0, :+) > i
end
abundantSums = []
#this 2 dimensional loop will find the every possible sum of 2 abundant numbers from which we got in the last for loop and push them into another array "abundantSums"
for i in 0...abundantNumbers.length
for j in i...abundantNumbers.length
sum = abundantNumbers[i] + abundantNumbers[j]
abundantSums.push(sum) if sum <= 28123
end
end
abundantSums = abundantSums.uniq.sort #remove duplicates and sort the array
notSums = []
for i in 1..28123 #find numbers which are not the sum of 2 abundant numbers and push them into the array "notSums"
notSums.push(i) if (abundantSums.include? i) == false
end
print notSums.inject(0, :+) #print out sum of array elements that are not sums of abundant numbers发布于 2018-08-28 03:24:21
问题是如何处理这些因素,数组中有包含因素的重复项,这是修复方法:
def factors(num) # function that returns array of factors
factorsNums = []
for i in 1..Math.sqrt(num).ceil
if num % i == 0
factorsNums.push(i) if i != num && !factorsNums.include? i
factorsNums.push(num / i) if ((num / i) < num) && ((factorsNums.include? (num / i)) == false)
end
end
factorsNums
endhttps://stackoverflow.com/questions/52049268
复制相似问题