samedi 23 novembre 2019

How to judge whether number in [2,10000000] is prime at compile time?

Actually,10000000 is really large.Via g++,maybe you will get "cc1plus.exe: out of memory allocating ??? bytes".

I have a clumsy idea:

First design a constexpr function isPrime.

constexpr bool isPrime(int x){...}

So isPrime(1),isPrime(2)... will be computed at compile time.

Then

#define UP1(e,p) e(p##1);e(p##2);e(p##3);e(p##4);e(p##5);e(p##6);e(p##7);e(p##8);e(p##9);
#define UP2(e,p) e(p##1);e(p##2);e(p##3);e(p##4);e(p##5);e(p##6);e(p##7);e(p##8);e(p##9);
#define UP3(e,p) e(p##1);e(p##2);e(p##3);e(p##4);e(p##5);e(p##6);e(p##7);e(p##8);e(p##9);
#define UP4(e,p) e(p##1);e(p##2);e(p##3);e(p##4);e(p##5);e(p##6);e(p##7);e(p##8);e(p##9);
#define UP5(e,p) e(p##1);e(p##2);e(p##3);e(p##4);e(p##5);e(p##6);e(p##7);e(p##8);e(p##9);
#define UP6(e,p) e(p##1);e(p##2);e(p##3);e(p##4);e(p##5);e(p##6);e(p##7);e(p##8);e(p##9);
#define UP7(e,p) e(p##1);e(p##2);e(p##3);e(p##4);e(p##5);e(p##6);e(p##7);e(p##8);e(p##9);
#define ASSIGN(x) a[x]=isPrime(x)
#define D1(x) UP1(ASSIGN,x)
#define D2(x) UP2(D1,x)
#define D3(x) UP3(D2,x)
#define D4(x) UP4(D3,x)
#define D5(x) UP5(D4,x)
#define D6(x) UP6(D5,x)
#define D7(x) UP7(D6,x)

D7()

So it will generate a[1]=isPrime(1);a[2]=isPrime(2);...a[9999999]=isPrime(9999999);;;...And array "a" stores the annswer.

Obviously it's not elegant at all.

Are there any pretty,doable,no-compile-error methods to solve that?

Aucun commentaire:

Enregistrer un commentaire