C language to implement statistical primes and sum code sharing

  • 2020-04-02 02:44:23
  • OfStack

The title comes from the PAT platform, which is a bit of a puzzle. They want to output the number of primes in a given interval and sum them up. The specific idea is to use the loop to judge the prime number, pass the result to the control variable, and then the control variable to judge whether to perform self-increment and sum. Of course, it's important to note that 1 is neither prime nor composite.

Here is the code:


#include <stdio.h>
int main ()
{
 int a=0,b=0;
 int n=0,sum=0;
 int x=0,i=0;
 scanf("%d %d",&a,&b);
 int check=1; //Suppose it is a prime number
 for (x=a;x<=b;x++){
     check=1;
     for (i=2;i<x;i++){
       if (x%i==0){
       check=0;
       break;
       }      //This loop is used to determine whether it is a prime number, iterate over the number less than x, assign a value of 0 to the variable if there is one that divisible x, and jump out of the loop
     }
     if (check != 0 && x!=1){
       n++;
       sum+=x;
     } //This if is used to determine the check value passed in the previous loop and to add the determination of whether x is 1
 }
 printf("%d %d",n,sum);
 return 0;
}


Related articles: