0
我有一个问题,使得返回整数的素因式分解的代码。我知道我的代码给出了正确的因素,但我需要使用StackOfIntegers类。StackOfIntegers给出奇怪的结果
StackOfIntegers类似乎不能很好地处理重复项。当我输入120时,返回素数因子5,3和2。该输出缺少另外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;
}
}
你的问题到底是什么? – noinstance