java - 质数Java

标签 java primes

这是家庭作业,我已经做了大部分,但我觉得我的素数生成器已关闭,因为当我运行它时,它只会将 1 和 3 的 Y 值增加 5,而不是 1 到 100 之间的所有其他素数;

这是作业题

It's Joen's Birthday and his friends have hidden his gift somewhere in his       house.

Joen begins at the origin: (0,0)

He has to follow 100 commands. The first being command 1, the second being command 2, etc.

Only one of the following can be applied at once.

-If the command number is both prime and odd, he must take 5 steps ahead (up)
-Otherwise if the command number is both prime and even, he must take 3 steps backwards (down)
-Otherwise if the command number is even, he must take one step to the right.
-Otherwise if the command number is odd, he must take one step to the left

The following rule can be applied in addition to another rule
-If the command number is divisible by 7, he must take the quotient number of steps down.

Using a coordinate system, at what point is the gift hidden? Create a program that shows the steps Joen takes to find his hidden gift.

这是我的代码

import java.util.*;

public class Party{
public static void main(String[] args) {

    int counterCommand = 1;
    int x = 0;
    int y = 0;
    int temp;
    boolean isPrime=true;
    while (counterCommand <= 100) {
        int num=counterCommand;
        for(int i=2;i<=num/2;i++){
        temp=num%i;
        if(temp==0){
            isPrime=false;
            break;}
        }

        if (isPrime==true){
            if (counterCommand % 2 != 0){
                y = y + 5;
            }
                else {
                    y = y - 3;
                }
            }
            else{
                if (counterCommand % 2 != 0){
                    x = x - 1;
                }
                else{
                    x = x + 1;
                }

            }
            counterCommand = counterCommand + 1;
        }
        System.out.print(x + "," + y);
    }   
}

当我运行它时,Y 的值在任何不是 1 或 3(5、7、13 等)的 Prime 赔率下都没有增加,这是为什么?因为我知道我得到的 1,7 是不正确的

最佳答案

在我看来,您需要在循环内将 isPrime 重置为 true,目前您只设置一次,而不是针对数字中的每个迭代器。

因此,在找到第一个合数 (4) 后,您对素数的测试失败了。

关于java - 质数Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33873384/

相关文章:

java.lang.ClassFormatError : Duplicate method name&signature in class file 错误

java - 不正确的week_of_year

java - 创建实体管理器中的 Hibernate 错误 [java.lang.NoSuchMethodError : org. hibernate.cfg.Environment.verifyProperties(Ljava/util/Map;)V]

c++ - 如何编写一个快速函数来计算一个数的总除数?

python - 查找素数算法的时间复杂度

java - 如何修复 - 41 : non-static variable cannot be referenced from a static context -> What is the reason for this?

c++ - 在 C++ 中从另一个线程终止一个线程

java - Java 中素数算法的时间复杂度

java - 在 HashMap 中存储一个数组

java - 什么是 NullPointerException,我该如何解决?