pontz_rwのブログ

プログラミング等の備忘録

Volume0: 0008

4つの整数の和 | Aizu Online Judge

重複を許す組み合わせの数を求めます。

C++

dn - (a + b + c) より求めることで、forループが三重で済みます。

#include <iostream>
using namespace std;

int n;

int main()
{
    while (cin >> n) {
        int count = 0;
        for (int a = 0; a <= 9; ++a) {
            for (int b = 0; b <= 9; ++b) {
                for (int c = 0; c <= 9; ++c) {
                    int d = n - a - b - c;
                    if (0 <= d && d <= 9) ++count;
                }
            }
        }
        cout << count << endl;
    }
    return 0;
}

Python

itertools.product()を使用することで、直積を求めることができます。

product(range(10), range(10))は、(x, y) for x in range(10) for y in range(10)と等価です。

また、product(range(10), range(10))は、product(range(10), repeat=2)と等価です。

# coding: utf-8

from itertools import product

RANGE = range(10)

while True:
    try:
        n = int(input())
    except EOFError:
        break
    
    print(sum([1 for (a, b, c) in product(RANGE, repeat=3) if n - a - b - c in RANGE]))