三个数相加等于30问题的编程实现

描述

☐ + ☐ + ☐ = 30, ☐ 里填{1, 3, 5, 7, 9, 11, 13, 15} 可以重复填

当然结果是不存在的 不过如何验证是不是真的不存在呢

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// g++ -Wall -fomit-frame-pointer -funroll-loops -Ofast -msse4.2 -mavx -std=c++11 a.cpp -lm -o a
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
int main(void)
{
vector<int> nums = {1, 3, 5, 7, 9, 11, 13, 15};
for (auto i : nums)
for (auto j : nums)
for (auto k : nums)
if (i + j + k == 29)
cout << i << " + " << j << " + " << k << " = 30." << endl;
return 0;
}

Emacs Lisp

1
2
3
4
5
6
7
(setq nums '(1 3 5 7 9 11 13 15))
(loop for i in nums do
(loop for j in nums do
(loop for k in nums do
(if (= 30 (+ i j k))
(message "%d + %d + %d = 30" i j k)))))

C

来自这里

#include <stdio.h>

int main(void)
{
	const int c[8] = {1, 3, 5, 7, 9, 11, 13, 15};

	for (size_t i = 0; i != 6; ++i)
		for (size_t j = i + 1; j != 7; ++j)
			for (size_t k = j + 1; k != 8; ++k)
				if (c[i] + c[j] + c[k] == 30)
					printf("%d + %d + %d = 30\n", c[i], c[j], c[k]);

	return 0;
}

其实这个是有解的 因为题目里面没说进制 在其他进制下是有解的