我的输入是一个Integer
. 在该值之前,应该找到所有质数并将其打印在 5 列中,然后我必须对整数进行“质数分解”并打印结果。
挺好用的,就是太慢了。。。
public class Bsp07 {
public static void main(String[] args) {
System.out.println("Enter the upper bound for prime number search");
int n = SavitchIn.readLineInt();
int[] aZahlen = new int[n - 1];
for (int el = 0, zahl = 2; el != n - 1; el++, zahl++)
aZahlen[el] = zahl;
int p = 2, altesP; // next unmarked number
boolean aus = false; // when unmarked elements are "aus" (off)
while (aus == false) {
// marks Elements; using For loop since for-each loop doesn't work
for (int i = 0; i < aZahlen.length; i++) {
if ((aZahlen[i] % p == 0) && (aZahlen[i] != p))
aZahlen[i] = 0;
}
altesP = p; // merkt sich altes p
// update p, find next unmarked Element
for (int el : aZahlen) {
if ((el != 0) && (el > altesP)) {
p = el;
break;
}
}
// if p stayed the same unmarked elements are "aus" (off)
if (altesP == p)
aus = true;
}
int nervVar = 0;
for (int pr : aZahlen) {
if(pr==0)
continue;
System.out.print(pr + " ");
nervVar++;
if ((nervVar % 5 == 0)) System.out.print("\n");
}
/* Factorization */
System.out.print("\n" + n + " = ");
for (int i = 0, f = 0; n != 1; i++, f++) {
while(aZahlen[i]==0) i++;
/*
* If the prime divides: divide by it, print the prime,
* Counter for further continuous decrease with prime number if n = 1,
* Stop
*/
if (n % aZahlen[i] == 0) {
n /= aZahlen[i];
// So that the first time is not *
if (f != 0)
System.out.print(" * " + aZahlen[i]);
else
System.out.print(aZahlen[i]);
i--;
}
// So that f remains zero if no division by 2
else
f--;
}
System.out.println();
}
}
我在哪里可以节省一些资源?顺便说一句,我现在只能使用数组......对不起德国人的评论。只是如果一些真正不必要的长循环或类似的东西引起了你的注意
谢谢!