For a long time I was getting the error that it took too long to validate. I am no longer getting that error. Now it just says it's not giving the correct output.
The program completes for N=1000000 in "0" seconds.
Result for N= 1000000:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834]
Checking online, this appears to be the correct sequence (except for 0, which is listed online but the conditions specify only to search "natural numbers" which are integers greater than 0). I do have it set to handle N < 1, returning new long[0].
package com.codegym.task.task20.task2025;
import java.util.ArrayList;
import java.util.Arrays;
/*
Number algorithms
*/
public class Solution
{
public static int digits;
public static long[] getNumbers(long N)
{
if(N < 1)
{
return new long[0];
}
long[] result;
ArrayList<Long> nums = new ArrayList<>();
long[][] powers = genPowers(N);
long total;
String iAsString;
int stringLength;
for(long i = 1; i < N; i++)
{
total = 0;
stringLength = String.valueOf(i).length();
iAsString = String.valueOf(i);
for(int n = 0; n < stringLength; n++)
{
total += powers[Integer.parseInt(iAsString.substring(n,n+1))][stringLength];
}
if(total == i)
{
nums.add(i);
}
}
result = new long[nums.size()];
for(int i = 0; i < nums.size(); i++)
{
result[i] = nums.get(i);
}
return result;
}
public static void main(String[] args)
{
long a = System.currentTimeMillis();
System.out.println(Arrays.toString(getNumbers(1000)));
long b = System.currentTimeMillis();
System.out.println("memory " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (8 * 1024));
System.out.println("time = " + (b - a) / 1000);
a = System.currentTimeMillis();
System.out.println(Arrays.toString(getNumbers(1000000)));
b = System.currentTimeMillis();
System.out.println("memory " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (8 * 1024));
System.out.println("time = " + (b - a) / 1000);
}
public static long[][] genPowers(long N)
{
digits = String.valueOf(N).length();
long[][] powers = new long[10][digits+1];
for(int i = 0; i < 10; i++)
{
for(int n = 1; n <= digits; n++)
{
powers[i][n] = (long) Math.pow(i, n);
}
}
return powers;
}
}