0

I can get the prime factor of a number, but in the code,

static int[] factorsOf (int val) {
  int index = 0;
  int []numArray = new int[5];

  System.out.println("\nThe factors of " + val + " are:");
  for(int i=1; i <= val; i++)
  {
      if(val % i == 0)
      {   
          numArray [index] = i;
          val=val/i;
          index++;
      }
  }
  return numArray;
}

say a number is 21, so I get 1,3,7,0,0 because I decide the range of the array is 5, how can I erease the 0, make it becomes 1,3,7?

tonytonov
  • 25,060
  • 16
  • 82
  • 98
Charles Cai
  • 2,731
  • 4
  • 18
  • 10

1 Answers1

0

To answer your question directly, use:

int[] newArray = new int[3];
System.arraycopy(numArray, 0, newArray, 0, index);
return newArray;

However this isn't scalable. Here's how to do it easily for any sized result set using java's Collections framework:

static int[] factorsOf (int val) {
    List<Integer> primes = new ArrayList<Integer>();

    System.out.println("\nThe factors of " + val + " are:");
    for(int i=1; i <= val; i++) {
        if(val % i == 0) {   
            primes.add(i);
            val=val/i;
        }
     }
     return primes.toArray();
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • If System.arraycopy is not "scalable" (for whatever that means here - optimized?) half of the JDK breaks down. Just try to measure it performance against the alternatives. And guess what primes.toArray() will do: arraycopy. – Thomas Jung Jun 03 '11 at 06:40