【Project EulerにRubyで挑戦シリーズ】問12:Highly divisible triangular number
今回の問題 Highly divisible triangular number The sequence of t...
-2018.11.13
-RubyでProject Euler
-Ruby, Project Euler
スポンサーリンク
2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2**1000?
2**15 = 32768 であり, 各位の数字の和は 3 + 2 + 7 + 6 + 8 = 26 となる.
同様にして, 2**1000 の各位の数字の和を求めよ.
べき乗は「**」で計算できます。
計算結果の文字列を1文字ずつ切り取って配列にし
各要素を順に足し上げれば求める答えになります。
power_digit_sum というメソッドで定義しました。
def power_digit_sum(number:, index:)
(number**index).to_s.chars.map(&:to_i).inject(:+)
end
puts power_digit_sum(number: 2, index: 1000)
今回は Minitest というテスティングフレームワークを用いて
問題文の一例の通り正しい値で返ってくるかも確かめてみました。
require 'minitest/autorun'
require './no016/problem'
class ProblemTest < Minitest::Test
def test_problem
assert_equal 26, power_digit_sum(number: 2, index: 15)
end
end
スポンサーリンク