- 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;
}
推薦閱讀
- MySQL數(shù)據(jù)庫管理實戰(zhàn)
- Learn Type:Driven Development
- Java系統(tǒng)分析與架構(gòu)設(shè)計
- Vue.js前端開發(fā)基礎(chǔ)與項目實戰(zhàn)
- Mastering Articulate Storyline
- PhpStorm Cookbook
- Drupal 8 Module Development
- 微信小程序入門指南
- Python之光:Python編程入門與實戰(zhàn)
- PHP+MySQL+Dreamweaver動態(tài)網(wǎng)站開發(fā)從入門到精通(第3版)
- Learning Apache Cassandra
- Visual Basic程序設(shè)計習(xí)題與上機實踐
- Learning Modular Java Programming
- Visual Studio Code 權(quán)威指南
- SQL Server 2008中文版項目教程(第3版)