官术网_书友最值得收藏!

  • 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;
}
主站蜘蛛池模板: 南开区| 余江县| 梨树县| 克拉玛依市| 乌审旗| 永胜县| 临汾市| 盐源县| 崇仁县| 太保市| 邵阳县| 望都县| 辰溪县| 建昌县| 扎兰屯市| 鄂尔多斯市| 泉州市| 南郑县| 略阳县| 保康县| 阜南县| 招远市| 诏安县| 陆川县| 鄂州市| 密云县| 包头市| 磐石市| 临潭县| 边坝县| 当雄县| 吉林市| 友谊县| 钟山县| 界首市| 山东| 鹰潭市| 柘荣县| 额济纳旗| 怀宁县| 衡东县|