官术网_书友最值得收藏!

4. Largest prime smaller than given number

A prime number is a number that has only two pisors, 1 and the number itself. To find the largest prime smaller than a given number you should first write a function that determines if a number is prime and then call this function, starting from the given number, towards 1 until the first prime is encountered. There are various algorithms for determining if a number is prime. Common implementations for determining the primality appear as follows:

bool is_prime(int const num) 
{
if (num <= 3) { return num > 1; }
else if (num % 2 == 0 || num % 3 == 0)
{
return false;
}
else
{
for (int i = 5; i * i <= num; i += 6)
{
if (num % i == 0 || num % (i + 2) == 0)
{
return false;
}
}
return true;
}
}

This function can be used as follows:

int main()
{
int limit = 0;
std::cout << "Upper limit:";
std::cin >> limit;

for (int i = limit; i > 1; i--)
{
if (is_prime(i))
{
std::cout << "Largest prime:" << i << std::endl;
return 0;
}
}
}
主站蜘蛛池模板: 红原县| 桓台县| 英德市| 东乌珠穆沁旗| 百色市| 泉州市| 巩义市| 上栗县| 都安| 萨迦县| 聊城市| 杭锦后旗| 岳池县| 开平市| 庆元县| 巴中市| 平遥县| 会泽县| 外汇| 大同市| 东方市| 正镶白旗| 若尔盖县| 滦南县| 呼玛县| 南安市| 平远县| 隆昌县| 宁安市| 长岛县| 嵩明县| 黑山县| 和静县| 昔阳县| 抚远县| 平顺县| 高唐县| 闽清县| 民县| 双城市| 恭城|