1 /************************************************************************/ 2 /* 1 2 3 4 5 6 7 8 9 = 81 在1-9之間添加加減乘除號,使等式成立。 */ 3 /************************************************************************/ 4 #include <iostream> 5 using namespace std; 6 7 bool stop = false; //控制遍歷終止 8 int count_ = 0; //計算結果數量 9 int count_loop = 0; //計算循環次數 10 11 void trans(int* arr, int index) //從右往左遞增遍歷 12 { 13 if(index < 0) 14 return; 15 int temp = arr[index] / 4; 16 if(temp <= 0) //判斷是否需要進位 17 return; 18 arr[index] = arr[index] % 4; 19 if(index == 0) //判斷是否已經遍歷完 20 { 21 stop = true; 22 return; 23 } 24 arr[index - 1] += temp; 25 trans(arr, index - 1); 26 } 27 28 void show(int* symbol, int len) //處理每次遍歷結果,並顯示正確項 29 { 30 float number[9]= {1,2,3,4,5,6,7,8,9}; 31 int symbol_copy[9]; 32 for(int i = 0; i < 9; ++i) 33 { 34 symbol_copy[i] = symbol[i]; 35 } 36 /* 37 計算出帶乘除號的結果,將前面的項置為0,符號沿用前面的符號 38 */ 39 for(int i = 0; i < len -1; i++) //合並乘除項 40 { 41 if(symbol_copy[i] == 2 || symbol_copy[i] == 3) 42 { 43 if(symbol_copy[i] == 2) //計算合並后的結果 44 { 45 number[i+1] = number[i] * number[i+1]; 46 } 47 else if(symbol_copy[i] == 3) 48 { 49 number[i+1] = number[i] / number[i+1]; 50 } 51 number[i] = 0;//合並后將前一個數置零 52 53 if(i == 0) 54 symbol_copy[i] = 0; 55 else 56 symbol_copy[i] = symbol_copy[i-1]; //乘除結果合並,符號替換成前面的符號 57 } 58 } 59 60 float num = number[0]; 61 for(int i = 0; i < len - 1; ++i) //計算結果 62 { 63 if(symbol_copy[i] == 0) 64 num += number[i+1]; 65 else if(symbol_copy[i] == 1) 66 num -= number[i+1]; 67 } 68 69 if(num == 81)//打印正確等式 70 { 71 count_++; 72 for(int i = 0; i < len -1; ++i) 73 { 74 cout<<i+1; 75 if(symbol[i] == 0) 76 cout<<"+"; 77 else if(symbol[i] == 1) 78 cout<<"-"; 79 else if(symbol[i] == 2) 80 cout<<"*"; 81 else if(symbol[i] == 3) 82 cout<<"/"; 83 } 84 cout<<"9=81"<<endl; 85 } 86 } 87 88 89 int main() 90 { 91 int symbol[9] = {0};// [0:+ 1:- 2:* 3:/] 92 int len = 9; 93 while(!stop) 94 { 95 show(symbol, len); 96 symbol[len-2]++; 97 trans(symbol, len-2); 98 count_loop++; 99 } 100 cout<<"有 "<<count_<<" 種可能"<<endl; 101 cout<<"遍歷了"<<count_loop<<"次"<<endl; 102 system("pause"); 103 return 0; 104 }