mathematica 发表于 2013-10-14 18:23:50

#include <cstdio>
#include <algorithm>
using namespace std;
#define A a
#define B a
#define C a
#define D a
#define E a
#define F a
#define G a
#define H a
#define I a
#define NUM(x1,x2,x3,x4) (x1*1000+x2*100+x3*10+x4*1)
int a={1,2,3,4,5,6,7,8,9};
int main()
{
        do{
                int x=NUM(0,0,A,B);
                int y=NUM(0,C,D,E);
                int z=NUM(F,G,H,I);
                if(x*y==z)
                {
                        printf("   %d\n* %d\n-----\n %d\n   \n",x,y,z);
                }
        }while(next_permutation(a,a+9));
        return 0;
}

chyanog 发表于 2013-10-15 18:08:21

用Mathematica写9个循环,Compile后运行时间<0.1s,主要时间都花在编译上了,如果没有C编译器的话速度编译时间可以忽略,但运行慢了,大概在1s左右Clear["`*"];
code1 = Block[{n = 9, cond, x},
cond = FromDigits*FromDigits] == FromDigits];
Fold[
   do, Table, {i, #2}]]], #], {x[#2 + 1], 1, n}] &,
   If &@Table, {i, n}],
   Range]
]

cf1 = With[{do = Do}, Compile[{Null}, #,RuntimeOptions -> "Speed", CompilationTarget -> "C"]] &@code1;
cf1 // AbsoluteTiming
页: 1 2 3 4 5 6 [7]
查看完整版本: 小学奥数求助