簡體   English   中英

素數 Java

[英]Prime Number Java

這是家庭作業,我有大部分,但我覺得我的素數生成器關閉了,因為當我運行它時,它只會將 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 等)的主要賠率下都不會增加,這是為什么? 因為我知道我得到的 1,7 是不正確的

在我看來,您需要在循環內將 isPrime 重置為 true,目前您只設置一次,而不是針對數字中的每個迭代器。

因此,在找到第一個合數 (4) 后,您對素數的測試失敗了。

    import java.util.Scanner;
public class PrimeNumber {
    public static void main(String[] args){
        System.out.println("Enter a Number");
        Scanner scn = new Scanner(System.in);
        int pr=scn.nextInt();
        int check=0;
        if(pr==2)
        {
        System.out.println("Entered Number is Prime");
        }
        else
        {
            for(int i=2; i<=pr; i++)
        {
            if(pr%i==0)
            {
                if(check==0)
                {
                System.out.println("Entered Number is not Prime");
                break;
                }
            }
            else
            {
                check=check+1;
            }
        }
    }
        if(check>1)
            System.out.println("Entered Number is Prime");
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM