Topic 1054: Level 2 C Language-Calculating the Sum of Prime Numbers

Input two positive integers m and n (m<n), find the sum of all prime numbers between m and n ( including m and n) , and define and call the function isprime(x) to determine whether x is a prime number (prime number is divided by A natural number other than 1 that is only divisible by itself).

Input format

m n

Output format

prime sum

Sample input

2 3

Sample output

5

My code: (no functions written)

The definition of a prime number is a number that is only divisible by 1 and itself ( 1 is not a prime number , pay attention to this)

So define a two-layer loop: for->for double-layer for loop. Note that the outer layer is executed once and the inner layer is completely looped.

-》The outer layer is a to b as the numbers to be divided, and the inner layer is as the divisor (when i%j==0 means, a number other than 1 and itself can divide i--》i is a non-prime number

break breaks out of all loops in this layer , continue is just the variable +1 in this layer

#include<iostream>
#include<cmath>
using namespace std;



int main() {
	int a, b;
	cin >> a >> b; //输入两个数

	bool isPrime = true;
	int sum = 0;
	for (int i = a; i <= b; i++) { //计算a到b之间素数的和
		isPrime = true;
		for (int j = 2; j <=sqrt(i); j++) {  //若从2到本身i能被整除 那就 不是素数
			if (i % j == 0) {
				isPrime = false;
				break;  //?break跳出j所有循环,而continue只是j++(如果后面有语句不执行)
			}
		}
		if (i == 1) 
			continue;
		else if (isPrime) 
			sum += i;
		}

	cout << sum;

	return 0;
}

Guess you like

Origin blog.csdn.net/qq_63999224/article/details/132927917