- 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;
}
推薦閱讀
- 無代碼編程:用云表搭建企業(yè)數(shù)字化管理平臺(tái)
- Three.js開發(fā)指南:基于WebGL和HTML5在網(wǎng)頁上渲染3D圖形和動(dòng)畫(原書第3版)
- Python Deep Learning
- Python Tools for Visual Studio
- Internet of Things with the Arduino Yún
- Mastering C# Concurrency
- TypeScript圖形渲染實(shí)戰(zhàn):基于WebGL的3D架構(gòu)與實(shí)現(xiàn)
- Mastering KnockoutJS
- C語言程序設(shè)計(jì)教程
- Python深度學(xué)習(xí):基于TensorFlow
- 精通MATLAB(第3版)
- Python+Tableau數(shù)據(jù)可視化之美
- 案例式C語言程序設(shè)計(jì)實(shí)驗(yàn)指導(dǎo)
- Learning Node.js for .NET Developers
- Java Web從入門到精通(第3版)