challenges

my solutions to various "programming challenge" problems
git clone https://wehaveforgeathome.hates.computer/challenges.git
Log | Files | Refs | LICENSE

023.rb (694B)


      1 #!/usr/bin/ruby
      2 
      3 def abundant? (n)
      4   sum = 1
      5   r = Math.sqrt(n)
      6   for d in (2...r)
      7     if n % d == 0
      8       sum += d + (n / d)
      9       if sum > n
     10         return true
     11       end
     12     end
     13   end
     14   if n % r == 0
     15     sum += r
     16   end
     17   sum > n
     18 end
     19 
     20 as = []
     21 as_hash = Hash.new
     22 
     23 for i in (12..28123)
     24   if abundant? i
     25     as.push i
     26     as_hash[i] = 1
     27   end
     28 end
     29 
     30 # cannot be written as the sum of two abundant numbers
     31 def cbwatsotabn? (n, as, as_hash)
     32   half = n / 2
     33   for a in as
     34     diff = n - a
     35     if diff < half
     36       return true
     37     end
     38     if as_hash[diff]
     39       return false
     40     end
     41   end
     42   return true
     43 end
     44 
     45 sum = 0
     46 for n in (1...28123)
     47   if cbwatsotabn? n, as, as_hash
     48     sum += n
     49   end
     50 end
     51 puts sum