读书笔记-《The Modern C++ Challenge》- Sum of naturals

文章目录

  • 0 个人介绍
  • Sum of naturals divisible by 3 and 5
    • 题目表述
    • 解决方案
    • 运行结果
    • 个人格言

0 个人介绍

作者: 赵萱婷
简介: 一个在工业软件领域摸爬滚打的新人,毕业于华科软院的一个普通人,希望未来能够在工业设计软件领域深耕越走越远的软件工程师。
个人格言:用心去感受你自己需要坚持的生活,未来慢慢会给你答案的。
知乎:https://www.zhihu.com/people/Tom_Zhao
STL项目地址: https://gitee.com/zhaotianyuCoding/using-stlex

Sum of naturals divisible by 3 and 5

题目表述

     Write a program that calculates and prints the sum of all the natural numbers divisible by either 3 or 5, up to a given limit entered by the user.
     编写一个程序,计算并打印所有根据用户输入范围限制内的可被3或5整除的自然数之和。

解决方案

     The solution to this problem is to iterate through all numbers from 3 (1 and 2 are not divisible 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 division 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:
     这个问题的解决方案是迭代从3(1和2不能被3整除,因此测试它们没有意义)到用户输入的限制的所有数字。使用模运算检查数字除以3和5的剩余部分是否为0。
     然而,要想将总和计算到一个更大的极限,诀窍是使用long long,而不是int或long作为总和,这将导致在将总和计算到100000之前出现溢出:

     因此,可以编写如下的代码来实现这个问题:

///
// Copyright (c) 2021, Tom Zhao personal. ("UsingSTLEx")
// This software is a personal tools project by Tom Zhao.
// Description:
///

#include 

using std::cin;
using std::cout;
using std::endl;

int main() {
  unsigned int limit = 0;
  cout << "Upper limit:";
  cin >> limit;
  unsigned long long sum = 0;
  for (unsigned int i = 3; i < limit; ++i) {
    if (0 == i % 3 || 0 == i % 5) {
      sum += i;
    }
  }
  cout << "sum= " << sum << endl;
}

     如果需要对应的程序文件,可以在如下链接找到:main.cpp

运行结果

读书笔记-《The Modern C++ Challenge》- Sum of naturals_第1张图片

个人格言

用心去感受你自己需要坚持的生活,未来慢慢会给你答案的。

你可能感兴趣的:(C++,STL,数据结构,c++,开发语言,算法,经验分享)