<> exercises 5-4 Using function to find the sum of prime numbers (20 branch )

This problem requires the realization of a simple function to determine the prime number , And using this function to calculate the sum of prime numbers in a given interval .

A prime number can only be 1 A positive integer divisible by itself . be careful ：1 It's not a prime ,2 It's a prime .

<> Function interface definition ：

int prime( int p );
int PrimeSum( int m, int n );

Where function prime When the user passes in the parameter p Returns when it is a prime 1, Otherwise return 0; function PrimeSum Return interval [m, n] Sum of all primes in . The title guarantees the parameters passed in by the user m≤n.

<> Example of referee test procedure ：

#include <stdio.h>
#include <math.h>

int prime( int p );
int PrimeSum( int m, int n );

int main()
{
int m, n, p;
scanf("%d %d", &m, &n); printf("Sum of ( "); for( p=m; p<=n; p++ ) { if(
prime(p) != 0 ) printf("%d ", p); } printf(") = %d\n", PrimeSum(m, n)); return
0;
}

/* Your code will be embedded here */

<> sample input ：

-1 10

<> sample output ：

Sum of ( 2 3 5 7 ) = 17

<> thinking ：

greater than 1, And can only be 1 The number divided by itself is prime
#include <stdio.h> #include <math.h> int prime( int p )// Prime return 1 { int i,flag=0;
for(i=2;i<p;i++) { if(p%i==0) break; } if(i==p) flag=1; return flag; } int
PrimeSum( int m, int n ) { int i,sum=0; for(i=m;i<=n;i++) { if(prime(i)==1) sum=
sum+i; } return sum; } int main() { int m, n, p; scanf("%d %d", &m, &n); printf(
"Sum of ( "); for( p=m; p<=n; p++ ) { if( prime(p) != 0 ) printf("%d ", p); }
printf(") = %d\n", PrimeSum(m, n)); return 0; }
Operation results ：

Technology
Daily Recommendation
views 0