首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么素数的证明计数器不工作?

为什么素数的证明计数器不工作?
EN

Stack Overflow用户
提问于 2019-10-01 14:22:12
回答 1查看 92关注 0票数 0

我在试着制作一个程序来检测主要因素。以下是流程:

  1. 检测如果一个数字是因子
  2. ,如果它是因子/ f,则从f-1,f-2,.
  3. 依次除以任何除数和余数,如果最终证明计数器= f-2,则证明计数器将增加
  4. ,它将通知素数因子

然而,当程序运行时,验证计数器部分的"for循环“将无法工作。

例如,当因子为6时,该证据只适用于:

  • 6 %5
  • 6 %4
  • 验证计数器= 2

然后跳起来寻找另一个因素

我不知道为什么会发生这种事?

(如果这个问题乱七八糟,我很抱歉)

int N= input.nextInt();

代码语言:javascript
运行
复制
    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");


            }

        }
    }
EN

回答 1

Stack Overflow用户

发布于 2019-10-01 15:56:54

3和2都除以6,所以代码中没有输出任何内容。如果您想要查看算法,尝试这些数字,那么除了证明的尝试之外,还需要打印出所有的尝试。

代码语言:javascript
运行
复制
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版本的算法,它显示了继续的计算。

代码语言: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);
  }
}

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58186879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档