- The Modern C++ Challenge
- Marius Bancila
- 149字
- 2021-06-25 22:01:23
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;
}
}
}
推薦閱讀
- SQL Server 從入門到項目實踐(超值版)
- 數據庫系統教程(第2版)
- Python從小白到大牛
- Cross-platform Desktop Application Development:Electron,Node,NW.js,and React
- JavaScript 網頁編程從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- Web Development with Django Cookbook
- Java開發入行真功夫
- 新編Premiere Pro CC從入門到精通
- Spring實戰(第5版)
- Mastering Python Networking
- Learning ELK Stack
- EPLAN實戰設計
- Mastering Predictive Analytics with Python
- 軟件測試技術指南
- Getting Started with Nano Server