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

  • 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;
}
主站蜘蛛池模板: 德钦县| 武山县| 腾冲县| 海盐县| 囊谦县| 河间市| 阿城市| 林甸县| 太湖县| 巴林左旗| 阿克陶县| 那坡县| 芦山县| 呼和浩特市| 灌云县| 鹤山市| 顺义区| 古浪县| 报价| 鲁山县| 从江县| 隆化县| 高淳县| 中牟县| 永州市| 湄潭县| 延庆县| 石林| 饶阳县| 双柏县| 兴仁县| 四川省| 凌海市| 饶河县| 兴城市| 吴堡县| 于田县| 内江市| 建瓯市| 铜山县| 托克逊县|