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

C Language Examples - Check Whether a Number Can Be Expressed as the Sum of Two Primes

C Language Examples - Check Whether a Number Can Be Expressed as the Sum of Two Primes

C Language Examples C Language Examples

Check whether a number can be expressed as the sum of two primes.

Example

#include

<

stdio.h

int

checkPrime

(

int

n

)

;

int

main

(

)

{

int

n

,

i

,

flag

=

0

;

printf

(

"

Enter a positive integer:

"

)

;

scanf

(

"

%d

"

, &

n

)

;

for

(

i

=

2

;

i

<=

n

/

2

; ++

i

)

{

// Check and determine

if

(

checkPrime

(

i

)

==

1

)

{

if

(

checkPrime

(

n

i

)

==

1

)

{

printf

(

"

%d = %d + %d

\

n

"

,

n

,

i

,

n

i

)

;

flag

=

1

;

}

}

}

if

(

flag

==

0

)

printf

(

"

%d cannot be decomposed into two primes.

"

,

n

)

;

return

0

;

}

// Check for a prime number

int

checkPrime

(

int

n

)

{

int

i

,

isPrime

=

1

;

for

(

i

=

2

;

i

<=

n

/

2

; ++

i

)

{

if

(

n

%

i

==

0

)

{

isPrime

=

0

;

break

;

}

}

return

isPrime

;

}

The output is:



输入正整数: 34

34 = 3 + 31

34 = 5 + 29

34 = 11 + 23

34 = 17 + 17

C Language Examples C Language Examples