This program is supposed to display the prime numbers in the range of 1-3000, but it only displays the prime numbers from 743-3000. How do I get it to print all prime numbers in the range?
Here is the program:
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
main()
{
unsigned long long num, divisible_num;
printf("The prime numbers in the range of 1 - 3000 are: \n");
for(num=1;num<=3000;num++)
{
for(divisible_num=2;divisible_num<=sqrt(num);divisible_num++)
{
if(num%divisible_num==0)
break;
}
if(num%divisible_num!=0)
{
printf("%lu\n", num);
}
}
getchar();
}
The foremost thing to do is to get the sqrt
call out of that for loop. You may compute it once. Better still, remove it all together with
for(divisible_num=2;divisible_num * divisible_num<=num;divisible_num++)
A number is prime if it is not divisible by any of the prime numbers less than or equal to the sqrt(num).
int prime = 1;
for(divisible_num=2;divisible_num * divisible_num<=num;divisible_num++) {
if (num % divisible_num == 0) {
prime = 0;
break;
}
}
if (prime) {
//print the num
}
Your outer loop must also start from 2.
When I ran your code it ranged from 1-3000. I'm not sure what your problem is. The get char() seems a little out of place.
Also once checking two, you don't have to divide by any more even numbers. This code works from 3 - 3000
for(num=3;num<=3000;num++)
{
int prime = (num%2 != 0);
long root = sqrt(num);
for(divisible_num=3;prime && divisible_num <= root;divisible_num+=2)
{
if(num%divisible_num==0){
prime = 0;
}
}
if(prime)
{
printf("%lu\n", num);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.