开发者

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("\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?


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("\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.

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


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


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


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.

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

//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

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


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;

  }

  }


Rework an algorithm for working with big numbers using BigInteger class. Try this:

import java.math.BigInteger;

class NumbersFactorization {
    public void printPrimeNumbers(String bigNumber) {
        BigInteger number = new BigInteger(bigNumber);
        for (BigInteger i = BigInteger.TWO; i.compareTo(number) <= 0; i = i.add(BigInteger.ONE)) {
            while(number.remainder(i) == BigInteger.ZERO) {
                System.out.print(i + " ");
                number = number.divide(i);
             }
        }
        if (number.compareTo(BigInteger.TWO) > 0)  System.out.println(number);
    }
}


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

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

You can take a square root of val for comparison and start iterator by value 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜