C語言 實現列舉演算法策略
阿新 • • 發佈:2020-12-29
列舉演算法本質上是搜尋策略
主要用於:不定方程,排列組合,暴力演算法
特點:
反思:要考慮時間,資料量不大時(對物件經行評估)
請反思這句話的涵義:對資料量的理解以及時間的理解,揚長避短的思想是要有的。
/* function:find the special number(three number ) */ #include<stdio.h> int main() { int a;//個位 int b;//十位 int c;//百位 int i;//迴圈變數 for (i = 100; i <= 999; i++) { a = i % 10;//取到個位 b = i / 10 % 10;//取到十位 c = i / 100;//取到百位 if (a* a* a + b * b * b + c * c * c == i) { printf("%d ", i); } } return 0; }
百錢買百雞問題也是如此
#include<stdio.h> int main() { int x, y, z;//分別為公雞,母雞,小雞 printf("公雞 母雞 小雞\n"); for (x = 0; x <= 20; x++) { for (y = 0; y <= 33; y++) { for (z = 0; z <= 100; z++)//不可能超過三百,因為百錢買百雞 { if ((z%3==0)&&(x + y + z ==100)&& (5 * x + 3 * y + z / 3 == 100)) { printf("%d %d %d\n", x, y, z); } } } } }