0
0

More than 1 year has passed since last update.

[Ruby] AtCoder過去問 B - Exponential

Posted at

はじめに

AtCoder過去問B問題をRubyで解いてみました。
よろしくお願いします。

問題はこちらから確認してください↓

B - Exponential

まずは入力をうけとります。
また、1が入っている配列を作っておきます。

x = gets.to_i
ary = [1]

このあとwhile文を使うのですが、そのとき1×1はどれだけ繰り返しても1で無限ループへ突入するため、配列には初めから1を入れておきます。

1は初めから入っているので2~xまでのeach文を作成します。iという数字はこの後の処理の中でも固定しておきたいのでコピーとして変数jを用意してiを代入しておきます。

x = gets.to_i
ary = [1]
(2..x).each do |i|
  j = i

続いてwhile文を作成します。i × jの答えがxより大きくなったときは処理を終了させます。
i × jの答えがx以下の間はi × jを行いjに代入し、そのjを先ほど作成した配列に入れていきます。

x = gets.to_i
ary = [1]
(2..x).each do |i|
  j = i
  while i * j <= x
    j = i * j
    ary << j
  end
end

最後に出来上がった配列の中で一番大きい数字を出力すれば完成です。

x = gets.to_i
ary = [1]
(2..x).each do |i|
  j = i
  while i * j <= x
    j = i * j
    ary << j
  end
end

puts ans.max
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0