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

27 篇文章 0 订阅
9 篇文章 1 订阅

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

运行结果

在这里插入图片描述

个人格言

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值