我在编写返回整数的素数分解的代码时遇到问题。我知道我的代码提供了正确的因素,但我需要使用StackOfIntegers类。
StackOfIntegers类似乎没有很好地处理重复项。当我输入120时,返回素因子5,3和2。此输出缺少另外2个。
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number: ");
int number = input.nextInt();
StackOfIntegers stack = new StackOfIntegers(1);
int factor = 2;
while (true) {
if (number % factor == 0) {
number = number / factor;
stack.push(factor);
}
if (factor > number) {
break;
}
if (number % factor != 0) {
factor++;
}
if (number < 2) {
break;
}
}
System.out.println("\nPrime Factors: ");
for(int i = 0; i < stack.getSize(); i++) {
System.out.println(stack.pop());
}
input.close();
}
}
class StackOfIntegers {
private int[] elements;
private int size;
public static final int MAX_SIZE = 16;
/** Construct a stack with the default capacity 16 */
public StackOfIntegers() {
this(MAX_SIZE);
}
/** Construct a stack with the specified maximum capacity */
public StackOfIntegers(int capacity) {
elements = new int[capacity];
}
/** Push a new integer into the top of the stack */
public int push(int value) {
if (size >= elements.length) {
int[] temp = new int[elements.length * 2];
System.arraycopy(elements, 0, temp, 0, elements.length);
elements = temp;
}
return elements[size++] = value;
}
/** Return and remove the top element from the stack */
public int pop() {
return elements[--size];
}
/** Return the top element from the stack */
public int peek() {
return elements[size - 1];
}
/** Test whether the stack is empty */
public boolean empty() {
return size == 0;
}
/** Return the number of elements in the stack */
public int getSize() {
return size;
}
}
答案 0 :(得分:1)
问题是你正在递增i
,但仍然将它与堆栈的当前大小进行比较,这在每次迭代中也在减少。
您可以在size
循环之前将堆栈的大小存储在新变量for
中,或者您可以只有while
循环,并且堆栈不为空,pop
并打印元素。