打印素数

来源:转载

/*
打印素数,下面是6个实现打印输入数以内的所有素数的函数,不仅实现打印素数,而且还进行计算运算的次数。
*/

void sushu1(){ int i, n, m; unsigned long count = 0; printf("请输入要打印素数的范围(N以内):"); scanf("%d", &m); for (n = 2; n <= m; n++) { for (i = 2; i < n; i++) { count++; if (n % i == 0) break; } if (i == n) { printf("%5d", n); } } printf("/n乘除运算的次数:%lu/n", count);}

运行情况:

void sushu2(){ int i, n, m; unsigned long count = 0; printf("请输入要打印素数的范围(N以内):"); scanf("%d", &m); for (n = 2; n <= m; n++) { for (i = 2; i < sqrt(n); i++) { count++; if (n % i == 0) break; } if (i > sqrt(n)) printf("%5d", n); } printf("/n乘除运算的次数:%lu/n", count);}

运行情况:

void sushu3(){ int i, n, m; unsigned long count = 0; printf("请输入要打印素数的范围(N以内):"); scanf("%d", &m); n = 2; printf("%5d", n++); for (; n <= m; n += 2) { for (i = 2; i < sqrt(n); i++) { count++; if (n % i == 0) break; } if (i > sqrt(n)) printf("%5d", n); } printf("/n乘除运算的次数:%lu/n", count);}

运行情况:

void sushu4(){ int i, n, m; unsigned long count = 0; printf("请输入要打印素数的范围(N以内):"); scanf("%d", &m); n = 2; printf("%5d", n++); for (; n <= m; n += 2) { for (i = 3; i < sqrt(n); i++) { count++; if (n % i == 0) break; } if (i > sqrt(n)) printf("%5d", n); } printf("/n乘除运算的次数:%lu/n", count);}

运行情况:

void sushu5(){ int i, n, m; int prime[500]; /*用来保存质数的数组*/ int ptr = 0; /*已经得到的质数个数*/ unsigned long count = 0; prime[ptr++] = 2; prime[ptr++] = 3; /*熟知的2,3为质数*/ printf("请输入要打印素数的范围(N以内):"); scanf("%d", &m); for (n = 5; n <= m; n += 2) { for (i = 1; i < ptr; i++) { count++; if (n % prime[i] == 0) break; } if (i == ptr) prime[ptr++] = n; } for (i = 0; i < ptr; i++) { printf("%5d", prime[i]); if ((i + 1) % 8 == 0) printf("/n"); } printf("/n乘除运算的次数:%lu/n", count);}

运行情况:

void sushu6(){ int i, n, m; int prime[500]; /*用来保存质数的数组*/ int ptr = 0, flag; /*已经得到的质数个数*/ unsigned long count = 0; prime[ptr++] = 2; prime[ptr++] = 3; /*熟知的2,3为质数*/ printf("请输入要打印素数的范围(N以内):"); scanf("%d", &m); for (n = 5; n <= m; n += 2) { flag = 1; for (i = 1; count++, prime[i] * prime[i] <= n; i++) { count++; if (n % prime[i] == 0) { flag = 0; break; } } if (flag) prime[ptr++] = n; } for (i = 0; i < ptr; i++) { printf("%6d", prime[i]); if ((i + 1) % 8 == 0) printf("/n"); } printf("/n乘除运算的次数:%lu/n", count);}

运行情况:



分享给朋友:
您可能感兴趣的文章:
随机阅读: