- The Modern C++ Challenge
- Marius Bancila
- 163字
- 2021-06-25 22:01:23
1. Sum of naturals pisible by 3 and 5
The solution to this problem is to iterate through all numbers from 3 (1 and 2 are not pisible by 3 so it does not make sense to test them) up to the limit entered by the user. Use the modulo operation to check that the rest of the pision of a number by 3 and 5 is 0. However, the trick to being able to sum up to a larger limit is to use long long and not int or long for the sum, which would result in an overflow before summing up to 100,000:
int main()
{
unsigned int limit = 0;
std::cout << "Upper limit:";
std::cin >> limit;
unsigned long long sum = 0;
for (unsigned int i = 3; i < limit; ++i)
{
if (i % 3 == 0 || i % 5 == 0)
sum += i;
}
std::cout << "sum=" << sum << std::endl;
}
推薦閱讀
- Node.js 10實戰
- Getting started with Google Guava
- 計算機圖形學編程(使用OpenGL和C++)(第2版)
- Mastering Articulate Storyline
- Django:Web Development with Python
- Hands-On Functional Programming with TypeScript
- 焊接機器人系統操作、編程與維護
- AppInventor實踐教程:Android智能應用開發前傳
- Learning Unreal Engine Android Game Development
- Python趣味編程與精彩實例
- Mastering Adobe Captivate 7
- ASP.NET Web API Security Essentials
- Mastering jQuery Mobile
- JavaWeb從入門到精通(視頻實戰版)
- Implementing NetScaler VPX?(Second Edition)