I have written a program that generates all possible numbers which can be represented by adding 2 cubes which have value less than N
For example: when \$N = 10, 1^3 + 2^3 = 9\$
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class AllNumberLessThanNasCubes {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("enter an integer n");
int n = new Scanner(System.in).nextInt();
System.out.println("all possible numbers are as follows ");
generateAllPossibleNumbers(n);
}
/**
* This function will generate all possible numbers less the {@link n} which can
* be represented as the sum of 2 cubes
* For eg.when N=10 , 1^3 + 2^3 = 9
* @param n
*/
public static void generateAllPossibleNumbers(int n) {
// TODO Auto-generated method stub
List<Long> cubes = new ArrayList<>((int) Math.cbrt(n));
List<Long> allSum = new ArrayList<>();
for (int i=1; Math.pow(i, 3)< n ;++i){
cubes.add((long) Math.pow(i, 3));
}
long sum=0 , tempSum=0;
int cubesSize= cubes.size();
System.out.println(cubes);
for (int i=0; i < cubesSize ;++i){
sum = cubes.get(i);
for (int j=i+1; j< cubesSize ; ++j){
tempSum = sum + cubes.get(j) ;
//System.out.println(tempSum);
if (tempSum >= n){
break;
}else{
allSum.add(tempSum);
}
}
}
System.out.println(allSum);
}
}
Is this the correct way to solve the problem? Is there an efficient way to solve it?
Except for error checking while taking input, what else can be improved?