LoginSignup
5
5

More than 5 years have passed since last update.

Project Eulerをシェル芸で解いてみる(Problem 6)

Last updated at Posted at 2016-01-06

概要

Project Euler1は、数学的な問題解決能力を要求する、プログラミング問題集である。
一般的なオンラインプログラミングジャッジとは異なり、解答するプログラミング言語は、特に限定されていない。
フォームに入力した値だけで正誤を判別するため、適切なアルゴリズムさえ考案できれば、あらゆるプログラミング言語で解答することが可能である。
そのため、Web上では様々な手法による解答が公開されている。

しかし、シェル芸2による解答は、私が探した限りでは、殆ど見つからなかった。
そこで、私自身の勉強も兼ねて、Project Eulerをシェル芸で解いてみることにした。

本記事では、Project EulerのProblem 6を、シェル芸で解いた際の過程を述べる。

実行環境

  • Arch Linux (x86_64, 4.3.3-2-ARCH)
  • bash (4.3.42)
  • GNU coreutils (8.24)
  • gawk (4.1.3)

問題文

[原文 (https://projecteuler.net/problem=6)]

The sum of the squares of the first ten natural numbers is,

1^2 + 2^2 + ... + 10^2 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)^2 = 55^2 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is $3025 − 385 = 2640$.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

[日本語訳 (http://odz.sakura.ne.jp/projecteuler/index.php?cmd=read&page=Problem%206)]

最初の10個の自然数について, その二乗の和は,

1^2 + 2^2 + ... + 10^2 = 385

最初の10個の自然数について, その和の二乗は,

(1 + 2 + ... + 10)^2 = 3025

これらの数の差は $3025 - 385 = 2640$ となる.
同様にして, 最初の100個の自然数について二乗の和と和の二乗の差を求めよ.

正答は、注釈3に記載する。

解法

1   #!/bin/sh
2   
3   (
4       ### 二乗の和の算出式の生成
5       seq -s ' ' 1 100 \
6       | # 1~100の出力
7       sed -e 's/[0-9]*/&^2/g' \
8       | # 1~100のそれぞれについて、二乗の算出式の生成
9       tr ' ' '+' \
10      | # 二乗の総和算出式の生成
11      sed -e 's/.*/(&)/' \
12      ; # (二乗の和) - (和の二乗)を計算するために、二乗の和の前後にかっこを付加
13  
14      ### 和の二乗の算出式の生成
15      seq -s ' ' 1 100 \
16      | # 1~100の出力
17      tr ' ' '+'
18      | # 1~100の総和算出式の生成
19      sed -e 's/.*/(&)^2/' \
20        # (総和)の二乗の算出式の生成
21  ) \
22  | # (二乗の和)と(和の二乗)の出力
23  awk 'BEGIN {RS=""} {print $2,"-",$1}' \
24  | # (二乗の和)と(和の二乗)の差を求める算出式の生成
25  bc
26    # (二乗の和)と(和の二乗)の差の出力

解法の解説

この解法による処理の詳細は、コードに記載してあるコメントの通りである。

雑記

  • 「こんな別解があるよ」や、「こうすればもっと効率化できるぜ」、「こう書けばエレガントですわよ」等の意見がありましたら、気軽に教えていただけますと幸いです🐺
  • 現在の進捗状況 -> https://github.com/gin135/Project_Euler/tree/master/sh

  • 今回は、解説は投げやり...

    • でも、今回の解答は、けっこうエレガントに出来たんじゃないかなと、自分でも思う。
    • だからこそ、コメントだけで解説が完結している訳だし。
    • とはいえ、 怖い 熟練シェル芸人さんの手に掛かれば、もっと 変態な 素敵な方法が出てきそうな予感。


  1. About - Project Euler (https://projecteuler.net

  2. シェル芸の定義 >> シェル芸 - 上田ブログ (https://blog.ueda.asia/?page_id=1434

  3. 25164150 

5
5
7

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
5
5