Finding the the sum of n amount of cubes

I am having difficulty writing a function for my program. I have to first ask the user to type in an integer. The user types in any integer, and the value is stored in the variable "num".

Then, I need to write a function called SumCubes that passes in "num" as its parameter value. The function SumCubes should find and return the sum of the first "num" cubes.

For example, if the user puts in the number 8, the function would return the value 1,296. I have all of the basic code already, I'm just confused on what algorithm would be going in the function body.

1
2
3
4
5
6
7
8
9
10
11
    #include <iostream>
    using namespace std;
    
    int main() {
        int num;
        
        cout << "Enter an integer" << endl;
	cin >> num;
        
        SumCubes(num);
      
What is the formula for getting 1,296 for inputting 8?

It is the sum of all the cubes of those numbers, for example:

(1^3) + (2^3) + (3^3) + (4^3) + (5^3) + (6^3) + (7^3) + (8^3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main()
{
    std::cout << "Enter number: \n";
    int num{};
    std::cin >> num;//input validation, etc
   //std::cin.ignore();
    int sum{};
    for (int i = 1; i <= num; ++i)
    {
      //one line of code required here, left as homework :))
    }
    std::cout << sum << "\n";
}
Last edited on
I'm just having trouble deciding on an algorithm to use for finding the sum of all the cubes :/
I'm just having trouble deciding on an algorithm to use for finding the sum of all the cubes :/

Work on getting the program to do what you intend first. Then optimise it with a more efficient algorithm.
http://mathschallenge.net/library/number/sum_of_cubes
^ is xor, a logical operation.
you want pow(n,3) or
n*n*n (faster, pow is wired for fractional exponents and slower)

there is probably a direct computation formula, but that is more math than programming. You can look it up or try to solve it. It will come down to coding up an equation, probably a simple one.


Topic archived. No new replies allowed.