C++中区间内质数计数
给定范围变量START和END。目标是在范围[START,END]内找到质数的数量。
我们将检查范围内的数字i是否为质数,方法是检查除1以外的任何数字是否完全整除它,并且该数字在1和i/2之间。如果是质数,则递增计数。
让我们通过例子来理解。
输入
Start=1 End=20
输出
Primes in Ranges : 8
解释
Primes between 1 and 20 are: 2,3,5,7,11,13,17,19.
输入
Start=100 End=200
输出
Primes in Ranges : 21
解释
Primes between 100 and 200 are: 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
下面程序中使用的方法如下
我们将范围变量作为START和END。
函数countPrimes(int strt,int end)返回范围内质数的计数。
将初始变量count设为0。
使用for循环从i=strt遍历到i <=end
取每个数字i并使用isprime(i)检查它是否为质数。
函数isprime(int num)如果数字是非质数则返回0,如果它是质数则返回1。
循环结束后,返回count作为结果。
示例
#include <bits/stdc++.h> using namespace std; int isprime(int num){ if (num <= 1) return 0; for (int i = 2; i <= num/2; i++){ if (num % i == 0) { return 0; } } return 1; //if both failed then num is prime } int countPrimes(int strt,int end){ int count=0; for(int i=strt;i<=end;i++){ if(isprime(i)==1) { count++; } } return count; } int main(){ int START=10, END=20; cout <<endl<<"Primes in Ranges : "<<countPrimes(START,END); return 0; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
如果我们运行上面的代码,它将生成以下输出:
Primes in Ranges : 4
广告