如何打印从1到1000的所有质数?
How to print all the prime numbers from 1 to 1000?
我正在尝试编写一个程序来遍历从一到一千的所有数字,但它不起作用。这是我到目前为止写的,我找不到问题:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int i = 0, j = 0, mona = 0;
bool prime = true;
//for each number between 1-1000
//i go over the numbers between two(It's ok if the number is divisible by 1,Every number is divisible
by 1) and this number (not including the number itself)
//if the number is divisible by any number, it is not a prime number
for(i = 2; i <= 1000; i++)
{
for (j = 2; j < i; j++) {
if (i % j == 0)
prime = false;
if (prime)
{
printf("prime number: %d\n", i);
mona++;
}
}
}
printf("number of prime numbers: %d", mona);
return 0;
}
这是我得到的输出:
prime number: 3
number of prime numbers: 1
我也看到了没有考虑到二号
你想要
for(i = 2; i <= 1000; i++)
{
prime = true;
for (j = 2; j < i; j++) {
很明显,如果每次外循环都测试标志,则每次外循环都需要对其进行初始化。
这可能是一个解决方案:
int i, int j;
int count=0;
int mona=0;
for(i = 2; i <= 1000; i++)
{
for (j = 2; j < i; j++) {
if (i % j != 0)
count++;
}
if (count==i-2){
printf("prime number: %d\n", i);
mona++;
}
count=0
}
用“count”计算除法余数不为0的次数。如果所有除法都满足前面的条件,则该数为质数。特定数第二个循环计算的除法数等于i-2.
我正在尝试编写一个程序来遍历从一到一千的所有数字,但它不起作用。这是我到目前为止写的,我找不到问题:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int i = 0, j = 0, mona = 0;
bool prime = true;
//for each number between 1-1000
//i go over the numbers between two(It's ok if the number is divisible by 1,Every number is divisible
by 1) and this number (not including the number itself)
//if the number is divisible by any number, it is not a prime number
for(i = 2; i <= 1000; i++)
{
for (j = 2; j < i; j++) {
if (i % j == 0)
prime = false;
if (prime)
{
printf("prime number: %d\n", i);
mona++;
}
}
}
printf("number of prime numbers: %d", mona);
return 0;
}
这是我得到的输出:
prime number: 3
number of prime numbers: 1
我也看到了没有考虑到二号
你想要
for(i = 2; i <= 1000; i++)
{
prime = true;
for (j = 2; j < i; j++) {
很明显,如果每次外循环都测试标志,则每次外循环都需要对其进行初始化。
这可能是一个解决方案:
int i, int j;
int count=0;
int mona=0;
for(i = 2; i <= 1000; i++)
{
for (j = 2; j < i; j++) {
if (i % j != 0)
count++;
}
if (count==i-2){
printf("prime number: %d\n", i);
mona++;
}
count=0
}
用“count”计算除法余数不为0的次数。如果所有除法都满足前面的条件,则该数为质数。特定数第二个循环计算的除法数等于i-2.