程序练习

来源:互联网 发布:迅雷 mac 速度0 编辑:程序博客网 时间:2024/05/16 05:43

找出N位数的质数,要求第一位都是质数,前两位也构成质数,以此类推,前N位构成质数

 

#include<iostream>#include <math.h>using namespace std;int res[8][200] = { { 2, 3, 5, 7 }, };int length[8] = {0,};int lowest_digit[5] = {0,};inline int is_prime(int i){if (i == 1)return false;int square = (int)sqrt((double)i);int x = 2;while (x <= square){if (i%x == 0){return false;}x++;}return true;}int main(){lowest_digit[0] = 1;lowest_digit[1] = 3;lowest_digit[2] = 5;lowest_digit[3] = 7;lowest_digit[4] = 9;length[0] = 4;int N, T, test_case;int calculated_number = 1;cin >> T;for (test_case = 0; test_case < T; test_case++){cin >> N;//输入的值在1~8的任意的数for (int i = 1; i <= N; i++){if (i > calculated_number){for (int x = 0; x < length[i - 2]; x++){for (int y = 0; y < 5; y++){int tmp = res[i - 2][x] * 10 + lowest_digit[y];if (is_prime(tmp)){res[i - 1][length[i - 1]] = tmp;length[i - 1]++;}}}calculated_number = i;}}cout<<"Case #"<<test_case + 1<<endl;for (int i = 0; i<length[N - 1]; i++)cout << res[N - 1][i] << endl;}}


 

 

0 0