How to output n prime numbers in the C language?
Below is a program written in C language that outputs the first n prime numbers.
#include <stdio.h>
int isPrime(int num) {
if (num <= 1) {
return 0;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}
void printPrimes(int n) {
int count = 0;
int num = 2;
while (count < n) {
if (isPrime(num)) {
printf("%d ", num);
count++;
}
num++;
}
}
int main() {
int n;
printf("请输入要输出的素数个数:");
scanf("%d", &n);
printf("前%d个素数为:", n);
printPrimes(n);
return 0;
}
Compile and run the program, enter the number of prime numbers to output, and the program will output the specified number of prime numbers.