Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

how to factor a number java

I need to factorize a number like 24 to 1,2,2,2,3. My method for that:

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

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

      return numArray;

  }

however, it is not working. Can anyone help me for that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have a few errors, you cannot create int array without size. I used array list instead.

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

    System.out.println("
The factors of " + val + " are:");
    for (int i = 2; i <= Math.ceil(Math.sqrt(val)); i++) {
        if (val % i == 0) {
            numArray.add(i);
            val /= i;
            System.out.print(i + ", ");
        }
    }
    numArray.add(val);
    System.out.print(val);
    return numArray.toArray(new Integer[numArray.size()]);
}

Full program using int[] according to your request.

public class Test2 {
    public static void main(String[] args) {
        int val = 5;
        int [] result = factorsOf(val);
        System.out.println("
The factors of " + val + " are:");
        for(int i = 0; i < result.length && result[i] != 0; i ++){
            System.out.println(result[i] + " ");
        }
    }

    static int[] factorsOf(int val) {
        int limit = (int) Math.ceil(Math.sqrt(val));
        int [] numArray = new int[limit];
        int index = 0;

        for (int i = 1; i <= limit; i++) {
            if (val % i == 0) {
                numArray[index++] = i;
                val /= i;
            }
        }
        numArray[index] = val;
        return numArray;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...