After reading some codes that worked with this "Armstrong Numbers" thing, I came up with this code (which is adapted from a code I found here).
The output for this code, which seems correct, is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 25, 36, 125, 216, 729]
memory 3918
time = 0
[1, 2, 3, 4, 5, 6, 7, 8, 9, 25, 36, 125, 216, 729, 1296, 16807, 32768, 59049]
memory 3918
time = 0
But the message I get is "The array returned by the getNumbers method is either missing elements or has extra elements.".
However, it seems to me that the problem is the usage of memory to run this code ("3918"). Does this "memory 3918" output mean 3918 MB of memory?
Or the problem is really about missing elements or extra elements in the returned array?
I'm trying to understand the other codes posted on the help topics, but they are really difficult for me, so that's why I'm insisting on this one.
Thanks!
package com.codegym.task.task20.task2025;
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
public static long[] getNumbers(long N) {
ArrayList<Long> list = new ArrayList<>();
int low = 0;
long high = N;
for(int S = low + 1; S < high; ++S) {
long M = 0;
long resultNumber = 0;
long originalNumber = S;
//find number of digits
while(originalNumber != 0) {
originalNumber /= 10;
++M;
}
originalNumber = S;
//resultNumber contains the sum of Mth power of its digits
while(originalNumber != 0) {
long remainder = originalNumber % 10;
resultNumber += Math.pow(remainder, M);
originalNumber /= 10;
break;
}
//add resultNumber to result array
if(resultNumber == S) {
list.add(resultNumber);
}
}
//convert ArrayList<Long> to long[] array
long[] result = new long[list.size()];
for(int i = 0; i < list.size(); i++) {
result[i] = list.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);
}
}