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

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;
}
}
}
主站蜘蛛池模板: 呼玛县| 台中县| 宜章县| 德惠市| 赤水市| 如皋市| 雷山县| 和龙市| 保山市| 礼泉县| 凉山| 上犹县| 东安县| 霍山县| 崇文区| 江川县| 娄底市| 合作市| 榆中县| 上林县| 通城县| 洪雅县| 三原县| 西昌市| 徐闻县| 宁德市| 康定县| 荔波县| 江城| 柘城县| 定日县| 怀仁县| 赞皇县| 青冈县| 正蓝旗| 湟源县| 亚东县| 革吉县| 南丹县| 黑山县| 文安县|