I am doing exercises from Programming in C by Kochan; just at the initial stage, chapter 5.
Here is the task:
Program 5.10 has several inefficiencies. One inefficiency results from checking even numbers. Because it is obvious that any even number greater than 2 cannot be prime, the program could simply skip all even numbers as possible primes and as possible divisors. The inner loop is also inefficient because the value of p is always divided by all values of d from 2 through. This inefficiency could be avoided by adding a test for the value of is_prime in the conditions of the for loop. In this manner, the for loop could be set up to continue as long as no divisor was found and the value of d was less than p. Modify Program 5.10 to incorporate these two changes.
Here is Program 5.10
// generate a table of prime numbers
#include <stdio.h>
int main (void)
{
int p, d;
_Bool is_prime;
for (p = 2; p <= 50; ++p)
{
is_prime = 1;
for (d = 2; d < p; ++d)
if (p % d == 0)
is_prime = 0;
if (is_prime) // or if (is_prime != 0); same
printf ("%i ", p);
}
printf ("\n");
return 0;
}
Here are two options I am trying to write, but both print out blank space; no numbers are produced. The first one might represent a completely wrong approach, but I can't see why the second wouldn't work.
Option 1:
// generate a table of prime numbers
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
int p, d;
bool is_prime;
/* start from p=2, do until p is less than 50,
and skip all even numbers */
for (p = 2; (p < 50) && (p % 2 != 0); ++p)
{
is_prime =1;
/* the inner for loop says: start from d = 2; do until
d is less than p, and also test if p is prime or not by
dividing p by d */
for (d = 2; d < p (p % d != 0 ? is_prime : !is_prime); ++d)
printf ("%i ", p);
}
printf ("\n");
return 0;
}
Option 2:
// generate a table of prime numbers
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
int p, d;
bool is_prime;
/* start from p=2, do until p is less than 50,
and skip all even numbers */
for (p = 2; (p < 50) && (p % 2 != 0); ++p)
{
is_prime =1;
/* the inner for loop says: start from d = 2; do until
d is less than p, and also test if p is prime or not by
dividing p by d */
for (d = 2; (d < p) && (p % d != 0); ++d )
/* this inner loop was supposed to print the number if
it is not divided by d */
printf ("%i ", p);
}
printf ("\n");
return 0;
}
I would be grateful for your help! I am new to programming.
Thank you!