简体   繁体   中英

how to make the range of an array as same as the number of the prime factors of a number

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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM