0
0

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 5 years have passed since last update.

文系学生のプログラミング学習12日目ーガウスとノンガウスの処理速度ー

Posted at

今回は1~Nまでの数字の和を求めるアルゴリズムを学習しました。
2種類あり、それぞれ処理速度に違いがあります。

すべて足していく方法

タイトルの通り単純にすべて足していく方法です。

def add_all_numbers_NonGauss(num_list):
    num = 0
    for i in range(0, len(num_list)):
        num += num_list[i]
    return num

[1, 2]なら1+2となります。1~100なら100回繰り返します。数字が多くなるほど計算に時間がかかってしまいます。

ガウスの方法

これは数学者ガウスが編み出した方法で、1~Nまでの和を求めるのに、n(n-1)/2を利用するものです。高校数学の数列の単元で学習したものです。

def add_all_numbers_Gauss(num_list):
    return((num_list[-1] + 1) * num_list[-1] / 2)

1~100までなら、N = (100+1)*(100/2) となり、どんなに数が増えても1回で計算できます。

自分は数学自体は数1A/2Bまでしか学んでいないのですが、プログラミングを勉強するにつれて数学の重要性を感じるようになってきました。数学も少し勉強しようと思います。

おわり

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?