I have gotten the right results but I get timed out.
I tried using an array to hold the factored values to speed up calculating the bigger numbers. but it still times out.
??
package com.codegym.task.task20.task2025;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
/*
Number algorithms
*/
public class Solution {
public static long[] getNumbers(long N) {
ArrayList <Long> res = new ArrayList<>(); // create an expandable array for collecting the result.
for (int i = 1;i < N; i++){ // for every natural number up to N
String number = String.valueOf(i); // convert the N to a string
char[] digit = number.toCharArray(); // Break the string apart into individual chars
long total = 0;
long[] factors = new long[10]; // create an array of 10 factored values based on the number of digits
for (int j = 0; j < 10; j++){
factors[j] = (long) Math.pow(j,digit.length);
}
for (char ch : digit){ // Use the factors array to match the digit and add it's value to the total
total += factors[Character.getNumericValue(ch)];
}
if (i == total){ // see if that total matches the original number and add it to the res array
res.add((long)i);
}
} // End of number search
Collections.sort(res); // sort the res
long[] result = new long[res.size()]; //convert the res to the required result array
for (int i = 0; i < res.size(); i++) {
result[i] = res.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);
}
}