1

次のコードがあります

#!/usr/bin/ruby -w
c = 1
d = Array.new(6965)  #6965 is the amount of abundant numbers below 28123 of which all numbers greater than that can be written as the sum of two abundant numbers
f = 0
while c < 28124      # no need to go beyond 28123 for this problem
  a = 0
  b = 1
  i = true           # this will be set to false if a number can be written as the sum of two abundant numbers
  while b <= c/2 + 1 # checks will go until they reach just over half of a number
    if c % b == 0    # checks for integer divisors
      a += b         # sums integer divisors
    end
    b += 1           # iterates to check for new divisor
  end
  if a > c           # checks to see if sum of divisors is greater than the original number
    d << c           # if true it is read into an array
  end
  d.each{|j|         # iterates through array
    d.each{|k|       # iterates through iterations to check all possible sums for number
                     # false is declared if a match is found. does ruby have and exit statement i could use here?
      i = false if c - j - k == 0
    }
  }
  c+=1               # number that we are checking is increased by one
                     # if a number cannot be found as the sum of two abundant number it is summed into f
  f += c if i == true
end
puts f

次のコードでは、配列に対して 2 回反復を実行しようとするdと、次のエラーが発生します。

euler23:21:inブロック (2 レベル) in ' from euler23:20:in block in ' from euler23:19:in ' -': nil can't be coerced into Fixnum (TypeError)
from euler23:21:in

each'
from euler23:20:in

each'
from euler23:19:in

私は Ruby に詳しくないので、これを解決するためのさまざまな試みは無駄でした。含める必要のあるライブラリがいくつかあるような気がしますが、私の調査ではライブラリについて言及されておらず、途方に暮れています。このコードは、2 つの豊富な数の合計として書ききれないすべての数を合計することを目的としています。Project Euler からの23 番目の質問です。

4

2 に答える 2

6

これを行う場合:

d = Array.new(6965)

6965 個のnil値の配列を作成します。

21 行目の前に次のテスト コードを追加する場合:

p [c,j,k]

次に、結果を取得します。

[1, nil, nil]

これは、jkが両方のnil値であることを示しています。配列内の空のアイテムを繰り返し処理しています。

の作成を次のように変更した場合d:

d = [] # an empty array, which in Ruby can change size whenever you want

...その後、コードが実行されます。(正しく動作するかどうかを確認するのに十分な時間は実行していませんが、少なくともかなりの時間はエラーなしで動作します。)


最後に、ランダムなスタイルのアドバイスをいくつか:

このコード:

while b <= c/2 + 1
  if c % b == 0
    a += b
  end
  b += 1
end

次のように、より簡潔に、より Ruby 風に書き直すことができます。

b.upto(c/2+1){ a+=b if c%b==0 }

同様に、このループ:

c=1
while c < 28124
  # ...
  c += 1
end

次のように書き換えることができます。

1.upto(28123) do |c|
  # ...
end

ループからの抜け出しについて質問する場合は、必要に応じて or またはbreakandnextthrowcatch使用できます(Ruby ではエラー処理には使用されません)。特定のネストされたループ レベルにジャンプします。

于 2013-04-02T16:33:29.223 に答える
3

以下のコードは間違っています。

d.each{|j|                     
d.each{ |k|             
p c,j,k  #1,nil,nil
i = false if c - j - k == 0 }}

なぜなら:

1 - nil - nil
#TypeError: nil can't be coerced into Fixnum
#      from (irb):2:in `-'
#      from (irb):2
#     from C:/Ruby193/bin/irb:12:in `<main>'
于 2013-04-02T16:33:42.977 に答える