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

Posted 赵萱婷

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了读书笔记-《The Modern C++ Challenge》- Sum of naturals相关的知识,希望对你有一定的参考价值。

文章目录

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 <iostream>

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的主要内容,如果未能解决你的问题,请参考以下文章

《Effective Modern C++》读书笔记

《Java: The Complete Reference》《Java 8 编程参考官方教程(第9版)》读书笔记

Software Architecture: The Hard Parts Modern Trade-Off Analyses for Distributed Architectures学习笔记

大教堂与集市(The Cathedral and the Bazaar)读书笔记

《The book of shaders》读书笔记

The art of multipropcessor programming 读书笔记-硬件基础2