Java 按升序打印数字的所有唯一素数因子
我是个初学者,完全糊涂了! 我需要显示一个数的所有素数因子,但在第一个代码中计算需要很长时间,在第二个代码中,如果我输入数字2,java会打印1和2,但我只需要2 示例:Java 按升序打印数字的所有唯一素数因子,java,Java,我是个初学者,完全糊涂了! 我需要显示一个数的所有素数因子,但在第一个代码中计算需要很长时间,在第二个代码中,如果我输入数字2,java会打印1和2,但我只需要2 示例: input 360 output 2 3 5 input 2 output 2 input 999999797 output 999999797 如果我输入99999797,则“时间限制” 我的错误是什么 for (d = 2; x > 1; d++) { if (x % d == 0) {
input 360
output 2 3 5
input 2
output 2
input 999999797
output 999999797
如果我输入99999797,则“时间限制”
我的错误是什么
for (d = 2; x > 1; d++) {
if (x % d == 0) {
x = x / d;
for (int i = 0; x % d == 0; i++) {
x = x / d;
}
System.out.println(d);
}
}
及
清理了第一个代码段的代码(实际上很好),代码如下:
int d = 2;
int step = 1;
while (x > 1) {
if (x % d == 0) {
System.out.println(d);
x /= d;
while (x % d == 0) {
x /= d;
}
}
d += step;
step = 2;
}
我添加了一个小优化,只测试了2、3、5、7、9等等,
证明许多除数不需要测试。一半的候选人
概括为跳过2、3、5:
对于模为2*3*5的数字:
// Unneeded code:
boolean[] dividable = new int[2*3*5]; // non-candidates to be skipped.
for (int i = 0; i < dividable.length; ++i) {
dividable[i] = i % 2 == 0 || i % 3 == 0 || i % 5 == 0;
}
// cycle length: 2*3*5 == 30.
// result: tfttt ttftt tftft ttftf tttft ttttf
// steps: 2 7 11 13 17 19 23 29 (8 from 30 candidates, a fourth)
请注意,这更难看,我还不能确定代码是否正确。您是否有指向您试图解决的问题的链接?哦,谢谢!!!我将对这个解决方案进行分析!我需要在任务中使用嵌套for循环,而不使用数组。这能比我上面的代码更优雅吗?我在第二个代码段中只使用有限的数组。第一个代码段仅改进了系数2I,添加了非数组版本,使用位和位操作<代码>位集也是可能的。逻辑是在模2*3*5的数字中,2、3和5的倍数处于固定位置。把它解释成评论。该死,我的脑子太笨了。。谢谢,这很有用!!
// Unneeded code:
boolean[] dividable = new int[2*3*5]; // non-candidates to be skipped.
for (int i = 0; i < dividable.length; ++i) {
dividable[i] = i % 2 == 0 || i % 3 == 0 || i % 5 == 0;
}
// cycle length: 2*3*5 == 30.
// result: tfttt ttftt tftft ttftf tttft ttttf
// steps: 2 7 11 13 17 19 23 29 (8 from 30 candidates, a fourth)
final int cycleLength = 2*3*5;
final int[] initialSteps = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
final int[] nextSteps = {1, 7, 11, 13, 17, 19, 23, 29};
int[] steps = initialSteps;
for (int b = 0; x > 1; b += cycleLength) {
for (int i = 0; x > 1 && i < steps.length; ++i) {
int d = b + steps[i];
while (x > 1) {
if (x % d == 0) {
System.out.println(d);
x /= d;
while (x % d == 0) {
x /= d;
}
}
}
}
steps = nextSteps;
}
final int cycleLength = 2*3*5;
final int common = 1<<7 | 1<<11 | 1<<13 | 1<<17
| 1<<19 | 1<<23 | 1<<29;
final int initialSteps = 1<<2 | 1<<3 | 1<<5 | common;
final int nextSteps = 1<<1 | common;
long steps = initialSteps;
for (int b = 0; x > 1; b += cycleLength) {
for (int i = 0, int mask = 1; x > 1 && i < cycleLength; ++i, mask <<= 1) {
if ((steps & mask) != 0) {
int d = b + i;
while (x > 1) {
if (x % d == 0) {
System.out.println(d);
x /= d;
while (x % d == 0) {
x /= d;
}
}
}
}
}
steps = nextSteps;
}