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

C Exercise 12

C Exercise 12

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Find the prime numbers between 101 and 200.

**Analysis:** Method for checking primes: divide the number by each integer from 2 to sqrt(the number). If it is divisible by any of them, the number is not prime; otherwise it is prime.

Example 1

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

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

//

#include

<

stdio.h

int

main

(

)

{

int

i

,

j

;

int

count

=

0

;

for

(

i

=

101

;

i

<=

200

;

i

++

)

{

for

(

j

=

2

;

j

<

i

;

j

++

)

{

// Break out of the loop if j is divisible by i

if

(

i

%

j

==

0

)

break

;

}

// Check whether the loop broke early; if j

if

(

j

=

i

)

{

count

++;

printf

(

"

%d

"

,

i

)

;

// Start a new line; use count to track and print a new line every five numbers

if

(

count

%

5

==

0

)

printf

(

"

\

n

"

)

;

}

}

return

0

;

}

The output of the above example is:



101 103 107 109 113 

127 131 137 139 149 

151 157 163 167 173 

179 181 191 193 197 

199

Example

#include

#include

// Function: check whether a number is prime

bool isPrime

(

int

num

)

{

   

if

(

num

<=

1

)

return

false

;

   

if

(

num

<=

3

)

return

true

;

   

if

(

num

%

2

==

0

||

num

%

3

==

0

)

return

false

;

   

for

(

int

i

=

5

;

i

i

<=

num

;

i

+=

6

)

{

       

if

(

num

%

i

==

0

||

num

%

(

i

2

)

==

0

)

return

false

;

   

}

   

return

true

;

}

int

main

(

)

{

   

printf

(

"List of primes between 101 and 200:\n"

)

;

   

for

(

int

i

=

101

;

i

<=

200

;

i

++

)

{

       

if

(

isPrime

(

i

)

)

{

           

printf

(

"%d "

,

i

)

;

       

}

   

}

   

printf

(

"\n"

)

;

   

return

0

;

}

Code analysis:

  1. isPrime function: Checks whether a number is prime. It first rules out some obvious non-primes, then uses the 6k +/- 1 form to check the remaining possible factors, improving efficiency.
  2. main function: Iterates over all integers between 101 and 200 and uses the isPrime function to check whether each number is prime. If it is, print it out.

100 Classic C Language Examples 100 Classic C Language Examples