1. 程式人生 > 其它 >列舉演算法:完美綜合式

列舉演算法:完美綜合式

技術標籤:習題演算法演算法c++

完美綜合式

在這裡插入圖片描述
思路:
先確定好9個數字的範圍為0~9,並且9個數字不能重複,然後9個數字根據需要組合成4個新的數,然後帶入題中的式子進行運算,確定好每個數字,最後輸出即可。

程式碼:

#include<time.h>
#include<math.h>
#include<stdio.h>
#include<iostream>
using namespace std;
int main() {
	double op,ed;
	double time;
	op=clock();

	int a[9] = {0};

	for
(a[0]=1; a[0]<=9; ++a[0]) for (a[1]=1; a[1]<=9; ++a[1]) for (a[2]=1; a[2]<=9; ++a[2]) for (a[3]=1; a[3]<=9; ++a[3]) for (a[4]=1; a[4]<=9; ++a[4]) for (a[5]=1; a[5]<=9; ++a[5]) for (a[6]=1; a[6]<=9; ++a[6]) for (a[7]=1; a[7]<=9; ++a[7]) for
(a[8]=1; a[8]<=9; ++a[8]) { bool flag=false; for (int i=0; i<8 && !flag; ++i) { for (int j=i+1; j<9; ++j) { if (a[i] == a[j]) { flag = true; break; } } } if(flag) continue
; int tmp = (int)pow(a[0],a[1]); int tmp1 = a[2]*10+a[3]; int tmp2 = a[4]*10+a[5]; int tmp3 = (a[6]*10+a[7])*a[8]; if (tmp1 == (tmp3-tmp)*tmp2) { for(int i=0; i<9; ++i) { printf("%d ",a[i]); } printf("\n"); break; } } ed=clock(); time=ed-op; printf("\n"); printf("time=%lfms\n",time); return 0; }

結果:
在這裡插入圖片描述