java java如何分解一个数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6223477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:55:44  来源:igfitidea点击:

how to factor a number java

java

提问by Charles Cai

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

我需要将 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;

  }

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

但是,它不起作用。任何人都可以帮助我吗?

回答by user658991

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

您有一些错误,您无法创建没有大小的 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()]);
}

Full program using int[] according to your request.

根据您的要求使用 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;
    }
}

回答by Ramesh PVK

A Working example

一个工作示例

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;

  }

  }

回答by if_zero_equals_one

public int[] primeFactors(int num)
{
    ArrayList<Integer> factors = new ArrayList<Integer>();
    factors.add(1);
    for (int a = 2;  num>1; )
        if (num%a==0)
        {
            factors.add(a);
            num/=a;
        }
        else
            a++;
    int[] out = new int[factors.size()];
    for (int a = 0; a < out.length; a++)
        out[a] = factors.get(a);
    return out;
}

回答by Paul Vargas

Are you looking a more faster way?:

您是否正在寻找更快的方法?:

static int[] getFactors(int value) {
    int[] a = new int[31]; // 2^31
    int i = 0, j;
    int num = value;
    while (num % 2 == 0) {
        a[i++] = 2;
        num /= 2;
    }
    j = 3;
    while (j <= Math.sqrt(num) + 1) {
        if (num % j == 0) {
            a[i++] = j;
            num /= j;
        } else {
            j += 2;
        }
    }
    if (num > 1) {
        a[i++] = num;
    }
    int[] b = Arrays.copyOf(a, i);
    return b;
}

回答by Neil

Most of the approaches suggested here have 0(n) time complexity. This can be easily resolved using binary search approach with 0(log n)time complexity.

这里建议的大多数方法的时间复杂度为 0(n)。这可以使用时间复杂度为0(log n) 的二进制搜索方法轻松解决。

What do you basically are looking for is called Prime Factors(although 1 is not considered among prime factors).

那你基本上是寻找被称为首相的因素(尽管1不是素数因素考虑)。

//finding any occurrence of the no by binary search
static int[] primeFactors(int number) {
    List<Integer> al = new ArrayList<Integer>();
    //since you wanted 1 in the res adn every no will be divided by 1;
    al.add(1); 

    for(int i = 2; i< number; i++) {
     while(number%i == 0) {
        al.add(i);
        number = number/i;
     }
  }
  if(number >2) 
     al.add(number);

  int[] res = new int[al.size()];
  for(int i=0; i<al.size(); i++)
    res[i] = al.get(i);

  return res;
}

Say input is 24, we keep dividing the input by 2 till all multiples of 2 are gone, the increase i to 3

假设输入是 24,我们继续将输入除以 2,直到 2 的所有倍数都消失,将 i 增加到 3

Here is a link to the working code: http://tpcg.io/AWH2TJ

这是工作代码的链接:http: //tpcg.io/AWH2TJ

回答by Nik

You just missed one step in if. Following code would be correct:

你只是错过了一步if。以下代码是正确的:

System.out.println("\nThe factors of " + val + " are:");

You can take a square root of val for comparison and start iterator by value 2

您可以取 val 的平方根进行比较并按值 2 启动迭代器

if(val % i == 0)
{   
   numArray1 [index] = i;
   val=val/i; //add this
  index++;
}

but here you need to check if index is 2,it is prime.

但在这里你需要检查索引是否为 2,它是prime.