エンジニアのソフトウェア的愛情

または私は如何にして心配するのを止めてプログラムを・愛する・ようになったか

「40 - 32 / 2 = 4!」新実装篇

前々々回前々回の続きで、 前回考察した結果を元に実装。

C++

#include <iostream>
#include <vector>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>

void print(int a, int b, int c)
{
    const int m = (a - b) / c;
    const int n =  a - b  / c;
    std::cout << (boost::format("(%1% - %2%) / %3% = %4%") % a % b % c % m) << std::endl;
    std::cout << (boost::format(" %1% - %2%  / %3% = %4%! = %5%") % a % b % c % m % n) << std::endl;
    std::cout << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        std::cerr << "usage: " << argv[0] << " <count>\n";
        return 0;
    }

    const int max = boost::lexical_cast<int>(argv[1]);

    int fn = 3 * 2 * 1;

    for(int n = 4;; ++n)
    {
        fn *= n;
        const int a_min  = fn + 1;
        const int a_max  = fn * 2;

        for(int a = a_min; a < a_max; ++a)
        {
            if(max < a)
            {
                return 0;
            }

            const int c_max = a / (a - fn);

            for(int c = 2; c <= c_max; ++c)
            {
                const int b = c * (a - fn);

                if(a <= b)
                {
                    break;
                }

                if((((a - b) % c) == 0) && (((a - b) / c) == n))
                {
                    print(a, b, c);
                }
            }
        }
    }

    return 0;
}

Haskell

import Text.Printf
import System

factorials  = scanl (*) 1 [1..]
factorial n = factorials !! n

values = [ (a, b, c, n) | n  <- [4..], 
                          fn <- [factorial n],
                          a  <- [fn + 1..((2 * fn) - 1)],
                          c  <- [2..(div a (a - fn))],
                          b  <- [c * (a - fn)],
                          (quotRem (a - b) c) == (n, 0)
         ]

print_abcn (a, b, c, n) = printf "(%d - %d) / %d = %d\n %d - %d  / %d = %d! = %d\n\n" a b c n a b c n (factorial n)

main = do
  args <- getArgs
  let max  = (read $ head args)::Int
  sequence_ $ map print_abcn $ takeWhile (\(a, _, _, _) -> a <= max) values