如何计算一个数字java

Cha*_*Cai 4 java

我需要将一个数字分解为24到1,2,2,2,3.我的方法:

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

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

      return numArray;

  }
Run Code Online (Sandbox Code Playgroud)

但它没有用.任何人都可以帮助我吗?

use*_*991 7

你有一些错误,你不能创建没有大小的int数组.我使用数组列表代替.

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

    System.out.println("\nThe 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()]);
}
Run Code Online (Sandbox Code Playgroud)

根据您的要求使用int []的完整程序.

public class Test2 {
    public static void main(String[] args) {
        int val = 5;
        int [] result = factorsOf(val);
        System.out.println("\nThe 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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Ram*_*PVK 0

一个工作示例

public class Main
{
public static void main(String[] args)
{
    System.out.println(factorsOf(24));
}

static List<Integer> factorsOf (int val) {

      List<Integer> factors  = new ArrayList<Integer>();
      for(int i=1; i <= val/2; i++)
      {
          if(val % i == 0)
          {
              factors.add(i);
          }
      }

      return factors;

  }

  }
Run Code Online (Sandbox Code Playgroud)