k = 1
for i in range(1, 23):
print("%d^3" % i, end='')
for j in range(i):
if (j == 0):
print(" = %d" % k, end='')
else:
print(" + %d" % k, end='')
k += 2
print("")
I had to learn how to suppress newlines.
Here is the output:
You are almost there…but the output should display the cube of the number as the sum of that many consecutive odd numbers. For example, the cube of 3 is 27, which is the sum of 3 numbers, i.e. 7 + 9 + 11; similarly the cube of 4 is 64, which is the sum of 4 numbers, i.e. 13 + 15 + 17 + 19…and so on.
The output should look the same as mentioned in the question.
The sequence produced by the second print was initially a rather ugly loop that I condensed using list comprehension first, then learned how to print on the fly without storing the list. I’ve built the algorithm after observing that:
#include <iostream>
using namespace std;
int main(){
int bCube = 1;
int additiveFactors = 1;
int num;
int limit;
cout << "Please enter the max num: ";
cin >> limit;
for (bCube; bCube <= limit; bCube++){
cout << bCube << "^3 = ";
for (int i = 0; i < bCube; i++){
num = additiveFactors+2*i;
cout << num;
if (i < bCube-1){
cout << " + ";
}
}
additiveFactors = num+2;
cout << endl;
}
}
from __future__ import print_function
x = input("Up to what integer shall we go? ")
odds = [i for i in range(1, x ** 3) if i % 2 == 1]
z = x ** 3
for i in range(1,x+1):
firstindex = sum((range(i)))
the_long_list = (odds[firstindex:(firstindex+i)])
cube = sum(the_long_list)
print("%d^3 = " %(i) + " + ".join([str(x) for x in the_long_list]) + " = %d" %(cube))
public static void displayCube(int n){
int index=1;
for (int i=1; i<=n; i++){
String s=i+"^3=";
long m=(long)(Math.pow(i,3));
while (m>0){
m-=index;
s+=index+"+";
index+=2;
}
s=s.substring(0,s.length()-1);
System.out.println(s);
}
I didn’t look at the answers before solving it myself, but I did forgot to print the results of several input values at the same time, so I made a change and wrapped everything into a loop.
It’s in javascript: https://repl.it/HgsC/4
In perl a nice one liner - for those who aren’t perl users shift pulls in this context takes the first element of @ARGV or the parameters… [ and perl -E executes the script turning on all the “cutting edge” features in this case say.
(1…10) is the amount of times you want to loop, here it does 10 loops.
For the part after the equals I just get every number from the smallest one to the biggest one and print them all with a step of 2.