C语言程序 输出所有小于n的素数(n >=2)

时间:2024-10-14 00:22:10

1、ubuntu 14.04 linux cgcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2

2、#include<stdio.h>#include <衡痕贤伎stdlib.h>int main(){ int *primes_array = NULL; int num = 0,i = 0,j = 0,index = 0,flag = 0; printf("please enter a num (2 <= n <= 100000) :\n"); scanf("%d",&num); if(num < 2){ printf("too small !!\n"); return 0; } if(num > 100000){ printf("too larger !!\n"); return 0; } primes_array =(int *)malloc(num*sizeof(int)); for(i=0;i<num;i++) primes_array[i] = 0; primes_array[0] = 2; index = 0; for(i=2;i<=num;i++) { for(j=0;j<=index;j++){ flag = i % primes_array[j]; if(flag == 0) break; } if(flag){ index ++; primes_array[index] = i; } } printf("the prime nums are (n < %d ):\n",num); for(i=0;i<=index;i++) { printf("%d,\n",primes_array[i]); } free(primes_array); return 0;}

3、xxx@linux:~/code# gcc -o primes primes.cxxx@linux:~/code# ./primesplease enter a num (2 <= n <= 100000) :13the prime nums are (n < 13 ):2,3,5,7,11,13,xxx@linux:~/code# ./primesplease enter a num (2 <= n <= 100000) :5the prime nums are (n < 5 ):2,3,5,

© 手抄报圈