所以我有这个任务,我一直在努力,欢迎任何帮助或反馈:)
问题
(显示质因数)编写一个程序,提示用户输入一个正整数并按降序显示所有最小因数。使用 StackOfIntergers 类。
这是我到目前为止所拥有的,程序编译并运行,但得到的是素数而不是素数。
package primefactors;
import java.util.Scanner;
public class PrimeFactors {
public static void main(String[] args) {
System.out.print("Enter a positive number: ");
Scanner scanner = new Scanner (System.in);
final int number = scanner.nextInt();
int count = 0;
StackOfIntegers stack = new StackOfIntegers();
// Repeatedly find prime factors
for (int i = 2; i <= number; i++)
if (isPrime(i)) {
stack.push(i);
count++; // Increase the prime number count
}
// Print the prime factors
System.out.println("The prime numbers are \n");
final int NUMBER_PER_LINE = 10;
while (!stack.empty()) {
System.out.print(stack.pop() + " ");
if (stack.getSize() % NUMBER_PER_LINE == 0)
System.out.println(); // advance to the new line
}
}
public static boolean isPrime(int number) {
// Assume the number is prime
boolean isPrime = true;
for (int divisor = 2; divisor <= number / 2; divisor++) {
//If true, the number is not prime
if (number % divisor == 0) {
// Set isPrime to false, if the number is not prime
isPrime = false;
break; // Exit the for loop
}
}
return isPrime;
}
}
* Update#2 * 所以我需要让主要因素起作用,所以这就是我在研究更多和编码后得到的结果。
有用。现在我需要让程序在一个漂亮的列表中显示素数和素数。
感谢您的反馈和建议。
import java.text.MessageFormat;
import java.util.Scanner;
public class PrimeFactor {
public static void main(String[] args) {
System.out.print("Enter a positive number: ");
Scanner scanner = new Scanner (System.in);
int number = scanner.nextInt();
int count;
StackOfIntegers stack = new StackOfIntegers();
for (int i = 2; i<=(number); i++) {
count = 0;
while (number % i == 0) {
number /= i;
count++;
}
if (count == 0) continue;
stack.push(i);
count++;
}
System.out.println("The prime factors are \n");
final int NUMBER_PER_LINE = 10;
while (!stack.empty()) {
System.out.print(MessageFormat.format("{0} ", stack.pop()));
if (stack.getSize() % NUMBER_PER_LINE == 0)
System.out.println(); // advance to the new line
}
}
}
StackOfInterger 类
public class StackOfIntegers {
private int[] elements;
private int size;
/** Construct a stack with the default capacity 16 */
public StackOfIntegers() {
this(16);
}
/** 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];
}
//whether the stack is empty */
public boolean empty() {
return size == 0;
}
/** Return the number of elements in the stack */
public int getSize() {
return size;
}
}