我在试着制作一个程序来检测主要因素。以下是流程:
然而,当程序运行时,验证计数器部分的"for循环“将无法工作。
例如,当因子为6时,该证据只适用于:
然后跳起来寻找另一个因素
我不知道为什么会发生这种事?
(如果这个问题乱七八糟,我很抱歉)
int N= input.nextInt();
for(int i =N; i>1; i--){
if(N%i == 0){
f = i;
int proof = 0;
System.out.println("factor:" + f);
for(int j = f-1; j>=1; j--){
if(f%j != 0){
proof++;
System.out.println("proved when j is " + j);
}
}
System.out.println("no of proof"+proof);
if(proof == f-2){
System.out.println(f + "is PRIME");
}
}
}
发布于 2019-10-01 15:56:54
3和2都除以6,所以代码中没有输出任何内容。如果您想要查看算法,尝试这些数字,那么除了证明的尝试之外,还需要打印出所有的尝试。
int N = input.nextInt();
for (int i = N; i > 1; i--) {
if (N % i == 0) {
int f = i;
int proof = 0;
System.out.println("factor:" + f);
for (int j = f - 1; j >= 1; j--) {
System.out.println("j: " + j); // <-- current value proving
if (f % j != 0) {
proof++;
System.out.println("proved when j is " + j);
}
}
System.out.println("no of proof" + proof);
if (proof == f - 2) {
System.out.println(f + "is PRIME");
}
}
}
下面是运行中的javascript版本的算法,它显示了继续的计算。
let N = 6;
for(let i = N; i > 1; i--) {
console.log(`${N} % ${i}`);
if (N % i === 0) {
let f = i;
let proof = 0;
console.log("factor:", f);
for(let j = f - 1; j >= 1; j--) {
console.log('j', j); // show attempts here
if (f % j !== 0) {
proof++;
console.log("proved when j is " + j);
}
}
if (proof === f-2) {
console.log(f + " is PRIME");
}
console.log("number of proofs: " + proof);
}
}
https://stackoverflow.com/questions/58186879
复制相似问题