思考過程
入力制約の確認
3 ≤ n ≤ 100
0 ≤ x ≤ 300
最大でも 161700 通りなので、全探索でも十分処理可能と判断できる。
解法の方針
方法①:三重ループによる全探索
1 から n の整数から 3 つの異なる数を選ぶすべての組み合わせ (i, j, k) を列挙。
条件は i < j < k かつ i + j + k == x。
条件を満たす組み合わせの数をカウントする。
方法②:組み合わせライブラリを使う(Ruby:combination / Python:itertools.combinations)
(1..n) の配列から 3 個取り出す全ての組み合わせを生成。
各組み合わせの和が x と一致するかを判定。
実装:Rubyコード(方法①:三重ループ)
def count_combinations(n, x)
count = 0
(1..n-2).each do |i|
(i+1..n-1).each do |j|
(j+1..n).each do |k|
count += 1 if i + j + k == x
end
end
end
count
end
# 入力処理
while line = gets
n, x = line.split.map(&:to_i)
break if n == 0 && x == 0
puts count_combinations(n, x)
end
実装:Rubyコード(方法②:combinationを使う)
def count_combinations_lib(n, x)
(1..n).to_a.combination(3).count { |a, b, c| a + b + c == x }
end
while line = gets
n, x = line.split.map(&:to_i)
break if n == 0 && x == 0
puts count_combinations_lib(n, x)
end
Python
方法① 三重ループ
def count_combinations(n, x):
count = 0
for i in range(1, n-1):
for j in range(i+1, n):
for k in range(j+1, n+1):
if i + j + k == x:
count += 1
return count
# 入力処理
while True:
n, x = map(int, input().split())
if n == 0 and x == 0:
break
print(count_combinations(n, x))
方法② 標準ライブラリ itertools.combinations
from itertools import combinations
def count_combinations_lib(n, x):
nums = range(1, n+1)
return sum(1 for comb in combinations(nums, 3) if sum(comb) == x)
while True:
n, x = map(int, input().split())
if n == 0 and x == 0:
break
print(count_combinations_lib(n, x))