0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python】【Ruby】約数の総和を出すプログラム!!

Last updated at Posted at 2021-09-11

 Pythonを学び始めたので、簡単なプログラムからひたすら作っています。今回は約数の総和を出すプログラムを作ってみました。

def calculate_divisor(num):
    divisor = [i for i in range(1,num + 1) if num % i == 0]
    return divisor

def calculate_limited_divisor(num,divisor_range):
    limited_divisor = [i for i in range(1,divisor_range + 1) if num % i == 0]
    return limited_divisor

num = int(input("約数の総和を出したい整数を入力してください:"))
divisor_range = int(input("和を出したい約数の範囲を指定してください:"))
result = calculate_divisor(num)
result2 = calculate_limited_divisor(num,divisor_range)

print("約数の数は" + str(len(result)) + "です")
print("約数の総和は" + str(sum(result)) + "です")
print((str(divisor_range) + "以下の約数の和は" + str(sum(result2)) + "です"))

 このようなコードであり、出力結果は以下のようになります。

約数の総和を出したい整数を入力してください:12600
和を出したい約数の範囲を指定してください:5000
約数の数は72です
約数の総和は48360です
5000以下の約数の和は29460です

 ただ約数の総和を出すだけでなく、12600の約数のうち、5000以下の約数の和を出すといったこともできるようにしています。
 範囲の指定はそこまで重要な機能ではないと考えたため、範囲の指定をした関数と、範囲の指定をしていない関数を2つ作り、一方を削除しやすいようにしました。この方が見やすいかなとも思いました。
 再利用性を真剣に考えるならもっと抽象化できそうです。

Rubyで作っていたプログラム

 また以前にはRubyで同じプログラムを作っていました。

def divisor(num,range)
  num_div = (1..num).select{ |count| num % count == 0 }
  range_div = (1..range).select{ |count| num % count == 0 }
  puts "約数の数は#{num_div.length}です"
  puts "約数の総和は#{num_div.sum}です"
  puts "#{range}以下の約数の和は#{range_div.sum}です"
end


puts "約数の総和を出したい整数を入力してください"
num = gets.to_i
puts "和を出したい約数の範囲を指定してください"
range = gets.to_i
divisor(num,range)

 ツッコミどころは感じつつも、ひとまずブログを書いてコードを見せることがモチベーションになり、コメントをいただくことが勉強になっています。


0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?