Time Limit: 2s Memory Limit: 192MB
Problem Description
Verify Nicomachus’s theorem, which states that the cube of any integer m can be expressed as the sum of m consecutive odd numbers.
Input Format
Any positive integer
Output Format
The cube of the number decomposed into a series of consecutive odd numbers
Sample Input
13
Sample Output
13*13*13=2197=157+159+161+163+165+167+169+171+173+175+177+179+181
Code
#include <iostream>
using namespace std;
int main() { int m; cin >> m;
int cube = m * m * m; int start = m * m - m + 1; // Calculate starting odd number
cout << m << "*" << m << "*" << m << "=" << cube << "=";
// Output m consecutive odd numbers for (int i = 0; i < m; i++) { cout << start + 2 * i; if (i < m - 1) { cout << "+"; } } cout << endl;
return 0;}
Output Result
Code Explanation(1) Input positive integer m cin >> m reads the input integer.(2) Calculate the cube value cube = m * m * m calculates the cube of m.(3) Determine the starting odd number Using the formula start = m * m – m + 1 to find the first odd number.(4) Output format First output m*m*m=cube= part. Then output m consecutive odd numbers: starting from start, adding 2 each time. Connect each odd number with +, without adding + after the last odd number.Mathematical Verification (taking m=13 as an example)13 cubed = 2197Starting odd number:13 squared – 13 + 1 = 169 – 13 + 1 = 15713 consecutive odd numbers: 157, 159, 161, …, 181Sum: This is an arithmetic sequence, first term 157, common difference 2, number of terms 13Sum = 13×157 + 2×(13×12)/2 = 2041 + 156 = 2197
C++ Basic Tutorial Collection
C++ Basic Materials
1. C++ Output
2. C++ Variables
3. C++ Input
4. C++ Expressions
5. IF Statements
6. IF Applications
7. WHILE Loop Statements
8. FOR Loop Statements
9. Arrays
10. One-Dimensional Arrays
11. Two-Dimensional Arrays
12. C++ Functions
13. C++ File Operations – Writing Files
If you find it interesting, please click on me



