LoginSignup
1
0

More than 3 years have passed since last update.

[基本情報技術者試験]うるう年の判定のアルゴリズムをPythonで書いてみた。

Posted at

概要

  • 基本情報技術者試験の午後の試験でアルゴリズムがあります。過去問を解いても理解ができません…。実際にアルゴリズムをPythonで書いて、理解を深めていきたいと思います。

  • 前回はユークリッドの互除法のアルゴリズムを書きました。

  • 今回はうるう年の判定のアルゴリズムから書いてみます。

うるう年の判定

アルゴリズム

  • 西暦が4で割り切れ、かつ、100で割り切れなければ、うるう年である。ただし、西暦が400で割り切れれば、うるう年である。どちらにも該当しないなら、うるう年ではない。

コード

# うるう年の判定を行うIsLeapYear関数
def IsLeapYear(Year):
    # 外側の分岐処理
    if Year % 4 == 0 and Year % 100 != 0: # この条件が真なら
        Ans = True # うるう年である
    else:
        # 内側の分岐処理
        if Year % 400 == 0: # この条件が真なら
            Ans = True # うるう年である
        else:
            Ans = False # うるう年ではない
    return Ans

print("実行結果:",IsLeapYear(2104))
print("実行結果:",IsLeapYear(2105))
print("実行結果:",IsLeapYear(2200))
print("実行結果:",IsLeapYear(2400))

実行結果

実行結果: True
実行結果: False
実行結果: False
実行結果: True

まとめ

  • うるう年の判定って意外とややこしいんだなー
  • 次回は配列の最大値をのアルゴリズムを書こうかな

参考

1
0
1

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