Middle M2018 Spring C Introduction and Advanced Exercise Set Function Question 6-1 Use Functions to Find the Sum of Prime Numbers (20 points)

function questions

6-1 Use functions to find the sum of prime numbers (20 points)

This problem requires the implementation of a simple function to determine prime numbers and a function to use this function to calculate the sum of prime numbers in a given interval.

A prime number is a positive integer that is only divisible by 1 and itself. Note: 1 is not a prime number, 2 is a prime number.

Function interface definition:

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

The function returns 1 when primethe parameter passed in by the user pis a prime number, otherwise it returns 0; the function returns the sum of all prime numbers in the PrimeSuminterval [ m, ]. nThe title ensures that the parameters passed in by the user are mn.

Example of the 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;
}

/* 你的代码将被嵌在这里 */

Input sample:

-1 10

Sample output:

Sum of ( 2 3 5 7 ) = 17
 

 
 1 int prime(int p)
 2 {
 3     int i;
 4     int flag;    /*素数1,非素数0*/
 5     if (p <= 1)
 6         flag = 0;
 7     else if (p == 2 || p == 3)
 8         flag = 1;
 9     else
10     {
11         for (i = 2; i <= sqrt(p); i++)
12             if (p%i == 0)
13             {
14                 flag = 0;
15                 break;
16             }
17         if (i == (int)sqrt(p) + 1)
18             flag = 1;
19     }
20     return flag;
21 }
22 
23 int PrimeSum(int m, int n)
24 {
25     int i;
26     int s = 0;
27     for (i = m; i <= n; i++)
28         if (prime(i) == 1)
29             s += i;
30     return s;
31 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325014507&siteId=291194637