解题思路:大于2的偶数都是合数,所以找的时候每次步进2。后面试除时只要除找到素数就行了
注意事项:
参考代码:
#include <stdio.h> #include <stdlib.h> typedef struct PRIME { int *prime; int primeCount; } primeList; primeList *initializationList(int length) { primeList *list = malloc(sizeof(primeList)); if (!list) exit(EXIT_FAILURE); list->prime = malloc(length * sizeof(int)); if (!list->prime) exit(EXIT_FAILURE); list->prime[0] = 2; list->primeCount = 1; return list; } int main(int argc, char *argv[]) { int length; scanf("%d", &length); primeList *list; list = initializationList(length); for (int i = 3; i <= length; i += 2) { for (int j = 0; j < list->primeCount; j++) { if (i % list->prime[j] == 0) break; if (list->prime[j] == list->prime[list->primeCount - 1]) { list->prime[list->primeCount] = i; list->primeCount++; break; } } } for (int i = 0; i < list->primeCount; i++) { printf("%d\n", list->prime[i]); } return 0; }
0.0分
0 人评分
C语言训练-舍罕王的失算 (C语言代码)浏览:1054 |
C语言程序设计教程(第三版)课后习题7.2 (C语言代码)浏览:569 |
C语言程序设计教程(第三版)课后习题11.3 (C语言代码)浏览:1059 |
printf基础练习2 (C语言代码)浏览:321 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:611 |
C语言训练-计算t=1+1/2+1/3+...+1/n (C语言代码)浏览:942 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:624 |
1113题解浏览:823 |
矩形面积交 (C++代码)浏览:1204 |
C语言程序设计教程(第三版)课后习题8.5 (C语言代码)浏览:710 |