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

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;
}
}
}
主站蜘蛛池模板: 汉川市| 镇康县| 大余县| 赤壁市| 武定县| 通许县| 共和县| 卫辉市| 志丹县| 上饶县| 靖边县| 富阳市| 连平县| 宁晋县| 庆元县| 丹寨县| 武山县| 建德市| 当涂县| 自治县| 宝坻区| 漯河市| 兴义市| 阿瓦提县| 东乌珠穆沁旗| 太和县| 营口市| 台中市| 晋宁县| 腾冲县| 五指山市| 嘉鱼县| 奉化市| 定兴县| 马龙县| 浙江省| 海兴县| 礼泉县| 东源县| 博客| 巴中市|