Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 36 - Find Primes Within 100

C Exercise 36 - Find Primes Within 100

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Find the prime numbers within 100.

**Program Analysis:** A prime number is also called a prime; there are infinitely many of them. A natural number greater than 1 that cannot be divided evenly by any natural number other than 1 and itself.

Program source code:

Example 1

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. All rights reserved.

//

#include

<

stdio.h

#include

<

math.h

int

main

(

)

{

int

n

=

0

;

for

(

int

i

=

2

;

i

<=

100

;

i

++

)

{

int

is_prime

=

1

;

// Assume i is prime

int

k

=

(

int

)

sqrt

(

i

)

;

for

(

int

j

=

2

;

j

<=

k

;

j

++

)

{

if

(

i

%

j

==

0

)

{

is_prime

=

0

;

// If i is divisible by j, then i is not prime

break

;

}

}

if

(

is_prime

)

{

printf

(

"

%d

"

,

i

)

;

n

++;

if

(

n

%

5

==

0

)

{

printf

(

"

\

n

"

)

;

}

}

}

return

0

;

}

Example 2

#include

#include

int

main

(

)

{

    bool is_prime

[

101

]

;

 

// Create a boolean array initialized to true

   

for

(

int

i

=

2

;

i

<=

100

;

i

++

)

{

        is_prime

[

i

]

=

true

;

   

}

   

for

(

int

i

=

2

;

i

i

<=

100

;

i

++

)

{

       

if

(

is_prime

[

i

]

)

{

           

for

(

int

j

=

i

i

;

j

<=

100

;

j

+=

i

)

{

                is_prime

[

j

]

=

false

;

           

}

       

}

   

}

   

int

n

=

0

;

   

for

(

int

i

=

2

;

i

<=

100

;

i

++

)

{

       

if

(

is_prime

[

i

]

)

{

           

printf

(

"%d "

,

i

)

;

            n

++;

           

if

(

n

%

5

==

0

)

{

               

printf

(

"\n"

)

;

           

}

       

}

   

}

   

return

0

;

}

The output of the above example is:



2 3 5 7 11 

13 17 19 23 29 

31 37 41 43 47 

53 59 61 67 71 

73 79 83 89 97 

100 Classic C Language Examples 100 Classic C Language Examples