简体   繁体   English

Java单独方法查找素数

[英]Java seperate method to find Prime numbers

I have written a program to find whether a number is prime or not. 我编写了一个程序来查找数字是否为质数。

The program has 2 methods: 该程序有2种方法:

  1. take input from user as to the numbers(stored in an array) 接受用户输入的数字(存储在数组中)

  2. take each element of the array and to find whether it is prime or not (this method return type is boolean ) 接受数组的每个元素,并确定它是否为素数(此方法的返回类型为boolean

Now my 2 nd method is always returning true for all values. 现在,我的第二种方法对于所有值始终返回true。

public static boolean Isprime(int x){

    boolean isprime = false;

    for(int m=2;m<x/2;m++){

        int temp = x%m;
        if(temp == 0){
            isprime = false;
        }
        else{
            isprime = true;
        }
    }
    return isprime;
}

Edited: 编辑:

public static  boolean Isprime(int x){

    boolean isprime = false;

    for(int m=2;m<=x/2;m++){

        int temp = x%m;
        if(temp == 0){
            isprime = false;
            break;
        }
        else{
            isprime = true; 
        }
    }
    return isprime;
}

PS - It is working for 9 as well. PS-它也适用于9。

You need to break out of for loop as soon as you found if it is not a prime and slighlty modified approach you can follow to omit some code and optimize it as well. 如果发现它不是素数和slighlty修改的方法,则需要立即中断for循环,您可以遵循该方法来省略一些代码并对其进行优化。

  public static  boolean Isprime(int x){
    boolean isprime = true;

    for(int m=2;m<=Math.sqrt(x);m++){

        int temp = x%m;
        if(temp == 0){
            isprime = false;
            break;
            }
      }
    return isprime;

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM