Exercise 4-11 Counting prime numbers and summing (20 points)

Exercise 4-11 Counting Prime Numbers and Summing (20 points)
This question requires counting the number of prime numbers in the interval of a given integer M and N and summing them.

Input format:
Input two positive integers M and N (1≤M≤N≤500) in one line.

Output format:
output the number of prime numbers and their sum in M ​​and N intervals in a row, separated by spaces.

Input sample:
10 31
Output sample:
7 143

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

int isPrime(int n)
    {
    
    
        int i;
        int flag=1;
        if(n==1)
            flag=0;
        else
            for(i=2;i<=sqrt(n);i++)
            {
    
    
                if(n%i==0)
                    flag=0;
            }
        return flag;
    }
int main()
{
    
    
    int m,n,i;
    int num=0,sum=0;
    scanf("%d %d",&m,&n);
    for(i=m;i<=n;i++)
    {
    
    
        if(isPrime(i))
        {
    
    
            num++;
            sum+=i;
        }
    }
    printf("%d %d",num,sum);
}

Guess you like

Origin blog.csdn.net/ChaoYue_miku/article/details/115015253