5. Write a program that adds up the squares and adds up the cubes of integers from 1 to N, where N is entered by the user:

Upper Limit: 5
The sum of Squares is 55
The sum of Cubes is 225
Do this by using just one loop that generates the integers. Of course, if you really needed to calculate these sums you would use the appropriate formulas:
12 + 22 + 32 + ... + n2 = n(n+1)(2n+1)/6
13 + 23 + 33 + ... + n3 = n2(n+1)2/4
Add these formulas to your program and print out their results as well as that of the explicit summations.

Dani AI

Generated

A compact, robust approach is to generate 1..N once and accumulate both sums inside that single loop, validate input, and pick integer arithmetic rather than floating-point helpers. posted the exercise; ’s comment about keeping it simple is on point, while ’s link is peripheral to the algorithm. The examples below show a clear pattern, note practical pitfalls (overflow, use of pow) and suggest verification with the standard closed-form expressions (add those separately if the assignment requires them).

#include <iostream>

int main() {
    long long n;
    if (!(std::cin >> n)) return 1;
    if (n < 1) return 1;

    long long sumSq = 0;
    long long sumCu = 0;
    for (long long i = 1; i <= n; ++i) {
        long long s = i * i;      // compute square once
        sumSq += s;
        sumCu += s * i;           // cube = square * i (all integer ops)
    }

    std::cout << "Sum of squares: " << sumSq << '\n';
    std::cout << "Sum of cubes: "   << sumCu << '\n';
    return 0;
}
n = int(input().strip())
if n < 1:
    raise SystemExit(1)

sum_sq = 0
sum_cu = 0
for i in range(1, n + 1):
    s = i * i
    sum_sq += s
    sum_cu += s * i

print("Sum of squares:", sum_sq)
print("Sum of cubes:", sum_cu)

Notes and troubleshooting

  • Prefer integer multiplication (ii and iii or si) instead of math.pow or std::pow to avoid floating-point rounding and extra cost.
  • C++ signed 64-bit (long long) will overflow for very large N (rough guideline: sums of squares safe up to a few million; sums of cubes safe to roughly 7–8×10^4). Use a bigger integer type (Boost.Multiprecision or __int128 where available) or Python for arbitrary precision if N may be large.
  • For correctness checks, compute the known closed-form results separately and compare them with the loop sums (the exercise expects both).

Recommended Answers

All 2 Replies

The problem practically gives away what you need to do. Have you been to class at all? Taken any notes? All you need is a simple (very simple) loop, a few counters, and the basic math knowledge to perform squares and cubes. Oh, and some form of getting input (also quite simple!).

commented: Makes you wonder what problems 1 to 4 were, since this is apparently #5 +29
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.