数字游戏
把数字1,2,…,9这9个数字填入以下含加减乘除与乘方的综合运算式中,使得该等式成立。要求9个数字均出现一次且仅出现一次,且数字1不能出现在乘和除的一位数中(即排除运算式中一位数为1的平凡情形)
c++代码实现
#include<iostream>
#include<vector>
using namespace std;
vector<int> result;
int visited[10];
void search()
{
if (result.size() == 9)
{
if ((result[0] * 10 + result[1])* result[2] + (result[3] * 100 + result[4] * 10 + result[5]) / (double)result[6] - (result[7] * 10 + result[8]) == 0
&& result[2] != 1 && result[6] != 1)
cout << result[0] << result[1] << " * " << result[2] << " + " << result[3] << result[4] << result[5] << " / " << result[6] << " - " << result[7] << result[8] << " == 0" << endl;
}
else
for (int i = 1; i < 10; i++)
{
if (!visited[i])
{
result.push_back(i);
visited[i] = 1;
search();
visited[i] = 0;
result.pop_back();
}
}
}
int main()
{
search();
return 0;
}