숫자 n을 소수의 곱으로 분해하는 방법을 만들려고합니다. 예를 들어 12를 인수 분해하면 3 x 2^2가됩니다. 코드의 첫 번째 블록은 n을 느슨한 숫자로 나눕니다. 따라서 12 = 3 x 2 x 2와 f에 넣습니다. 그런 다음 두 번째 블록은 지수가 f에서 발생하는 횟수로 지수를 계산하여 느슨한 숫자 대신에 p로 이러한 숫자를 저장하기로되어 있으므로 3 x 2 x 2 대신에 3^1 x 2^2가됩니다. 는 숫자의 밑과 지수를 저장하는 객체 Power로 끝난다.개체를 추가해도 arraylist가 비어있는 이유는 무엇입니까?
그러나 어떤 이유로이 코드는 빈 배열을 계속 반환합니다. 그리고 여러 번 살펴 본 후에도 왜 이런 일이 일어날 지 모릅니다. 내가 잘못하고있는 일이나 오해 한 일이 있습니까?
/**
* factorize n
*
* @param n the number to 'powerize'
* @modifies none
* @pre {@code 2 <= n}
* @return factorization of n
*/
public static List<Power> factorize(int n) {
List<Integer> f = new ArrayList<Integer>(); // f are factors
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
f.add(i);
n /= i;
}
}
List<Power> p = new ArrayList<Power>(); // p are the factors with powers
for (int j = 2; j <= n; j++) { //j will be the base
int e = 0; //exponent
for (int k = 0; k <= f.size(); k++) {
if (f.get(k) == j) {
e++;
}
}
p.add(new Power(j, e));
}
return p; //returns factors in powered form
}
필요에 따라 Power 객체의 코드를 추가합니다. 당신이 당신의 n
변수 값이 처음 for
주기 후 1
것을 볼 수 디버깅하는 경우
/**
* Record containing a base and an exponent.
*
* @inv {@code 0 <= base && 0 <= exponent}
*/
public static class Power { // BEGIN RECORD TYPE
/**
* The base.
*/
public int base;
/**
* The exponent.
*/
public int exponent;
/**
* Constructs a Power with given base and exponent.
*
* @param base the base
* @param exponent the exponent
* @pre {@code 0 <= base && 0 <= exponent}
* @post {@code \result.base == base && \result.exponent == exponent}
*/
public Power(int base, int exponent) {
this.base = base;
this.exponent = exponent;
}
} // END RECORD TYPE
디버거에서 단계별로 수행 했습니까? – Fildor
[디버깅] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)을 시도해 보셨습니까? 그렇다면 프로그램이 올바르게 작동하지 않는 가장 작은 번호는 무엇입니까? – yeputons
디버거는 즉시이를 보여 주었을 것입니다. 첫 번째 루프 'n = 1'이후에 완전히 배제되었습니다. 따라서 두 번째 루프는 0 번 반복을 수행합니다. – yeputons