PTA 6-1 Use functions to find sums of prime numbers

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 prime returns 1 when the parameter p passed in by the user is a prime number, otherwise it returns 0; the function PrimeSum returns the sum of all prime numbers in the interval [m, n]. The title ensures that the parameter m ≤ n passed in by the user.

Example of the referee test procedure:

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

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

intmain ()
{
    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 */

Input sample:

-1 10

Sample output:

Sum of ( 2 3 5 7 ) = 17
 

Author: Zhang Gaoyan

Unit: Zhejiang University City College

Time limit: 400ms

Memory Limit: 64MB

Code length limit: 16KB

 

my code:

/*
* =========================================================================== *
* @Author:        JovianHuang
* @Filename:    6-1.c
* @Description:    A question which numbered 6-1 in PTA. This question requires
                that the program be written to judging the prime number, and
                calculating the sum of primes in a given interval
* @Version: 1.0.0.180330_alpha
* =========================================================================== *
*/
#include <stdio.h>
#include <math.h>

int prime(int p)
{
    if (p <= 1)
        return 0;

    int bound = (int)sqrt(p) + 1;
    for (int i = 2; i < bound; i++)
    {
        if (!(p % i))
            return 0;
    }

    return 1;
}

int PrimeSum(int m, int n)
{
    int sum = 0 ;
    int p

    for( p=m; p<=n; p++ )
    {
        if( prime(p) != 0 )
            sum += p;
    }

    return sum;
}

int main(int argc, char const *argv[])
{
    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;
}

Guess you like

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