整数分解 - 代码不起作用

时间:2016-05-17 12:00:28

标签: java

如果我输入100,它应该是这样的:(2,2,5,5) 但它没有用。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class kgV {

    public static void main(String[] args) throws NumberFormatException, IOException {

        ArrayList<Integer> factors = new ArrayList<Integer>();
        boolean isPrime = true;

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int number = Integer.parseInt(in.readLine());


        for(int i=2; number>0; i++){
            for(int j=2; j<i; j++){
                if(i % j == 0){
                isPrime = false;
            }
        }

        if(isPrime && number % i == 0){
            number = number / i;
            factors.add(i);
        }

        isPrime = true;

        }
        System.out.println(factors.toString());
    }
}

这是它应该如何运作

100 = 2x2x5x5
27= 3x3x3
30= 2x3x5

2 个答案:

答案 0 :(得分:0)

试试这个。

public class NewClass {

  public static void main(String[] args) throws IOException {

  ArrayList<Integer> faktoren = new ArrayList<Integer>();    

  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  int zahl = Integer.parseInt(in.readLine());

  for (int i = 2; i <= zahl; i++) {
      while (zahl % i == 0) {
        faktoren.add(i);
        zahl /= i;
      }
  }
  System.out.println(faktoren.toString());
  }        
}

答案 1 :(得分:0)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Main {

public static void main(String[] args) throws NumberFormatException, IOException {

        ArrayList<Integer> faktoren = new ArrayList<Integer>();

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int zahl = Integer.parseInt(in.readLine());

        // While number is not 1 check for factors
        while (zahl != 1) {
            // Check each number till zahl for possible factor
            for (int i = 2; i <= zahl; i++) {
                if (zahl % i == 0) {
                    // update number and add factor
                    zahl = zahl / i;
                    faktoren.add(i);
                    break;
                }
            }
        }
        // Prime number will contain only itself in faktoren array
        boolean prim = faktoren.size() == 1;
        System.out.println(faktoren.toString());
    }
}