使用递归方法通过用户输入确定素数

时间:2013-04-26 18:47:19

标签: java math methods

我需要用Java创建一个程序来确定一个数字是否为素数。

用户应该输入任何数字,程序将确定它是否为素数,并显示“not prime”或“prime”。我的代码现在编译并运行,但它总是说数字不是素数,即使它是。

import java.util.Scanner;

public class PrimeNumber
{
 public static void main(String[] args)
  {
    Scanner input = new Scanner(System.in);
   int constant = 0;
   int variable = 0;
   System.out.println("Enter a Number to test if Prime or Not");
   constant = input.nextInt();
   variable = constant;
   double answer = 0.0;
   answer = testPrime(constant, variable);
   System.out.println(+answer);
   if (answer == 1)
    {
     System.out.println(+constant + " is a prime number.");
    }
   else
     {
     System.out.println(+constant + " is NOT a prime number.");
    }
   }

public static double testPrime(int number, int divide)
 {
  double prime = 0.0;
  prime = number%divide;
  if (prime > 0 && divide != number)
   {
    return testPrime(number, divide - 1);
   }
   else
   {
    return prime;
   }
 }
}

7 个答案:

答案 0 :(得分:2)

if (prime > 0 && divide != number)

这永远不会成真。因为你的分界和数字总是相等的。

看到您已分配variable=constant,这就是您传递给方法的内容

constant = input.nextInt();
variable = constant;
answer = testPrime(constant, variable);

那就是说,你需要走得那么复杂才能找出一个数字是否为素数。检查网络上的简单算法。例如,请参阅http://www.mkyong.com/java/how-to-determine-a-prime-number-in-java/

答案 1 :(得分:1)

不是答案,因为OP想要递归(我猜的是家庭作业)。

你只需要到n的平方根,看看它是否有除数(除了self之外的除数将是< sqrt(n))

    boolean isPrime(int n) {
            if(n % 2 == 0)return false;
            int till  = (int)java.lang.Math.pow(n, 0.5); //(int)n / 2;
            for(int i= 3;i<till;i+=2) {
                if(n % i == 0) 
                    return false;
            }
            return true;
        }

答案 2 :(得分:1)

我看到你想要递归,所以我将tgkprog的答案转换为递归方法(虽然他的效率肯定更高)。另外,如果输入不是素数,我想你可能想要返回一个素数因子?我只是推测这是从OP的双重而不是布尔值的返回值来判断的。我会返回一个int,因为返回一个双子是愚蠢的。

int isPrime(int n){ //starter function
      if(n<=1) return n; //sanity check for weird inputs
      if(n % 2 == 0) return 2; //2 is a prime factor
      int start  = (int)java.lang.Math.pow(n, 0.5);
      return isPrime(n,start-(start%2)); //makes start odd if it wasn't already
}

int isPrime(int n, int testval){ //recursive function
       if(testval<=1) return 1; //n is prime, return n since it has no prime factors
       if(n % i == 0) 
           return i; //found a prime factor!
       return isPrime(n,i-2);
}

答案 3 :(得分:0)

带递归

import java.util.Scanner;

public class PrimeRecursion
{
    static int dbg;
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter non 0 if you want debug :");
        dbg = input.nextInt();
        long constant = 3;
        long variable = 0;
        while(true){
            System.out.println("Enter a Number to test if Prime or Not (1 to exit)");
            constant = input.nextLong();
            if(constant < 3){
                if(constant == 2){
                    System.out.println("2 is a special prime");
                }
                return;
            }
            if(constant % 2 == 0){
                System.out.println(constant + " is NOT a prime number, even number.");
            }else{
                variable = (long)Math.pow(constant, 0.5);
                variable = (variable % 2 == 1) ? variable : variable + 1;//odd number
                double answer = 0.0;
                answer = testPrime(constant, variable);
                System.out.println("End answer : " + answer);
                if (answer == 1){
                    System.out.println(+constant + " is a prime number. answer : "  + answer);
                }
                else{
                    System.out.println(constant + " is NOT a prime number.answer : "  + answer);
                }
            }
            System.out.println();
        }
    }

    static double testPrime(long number, long divide)
    {
        double prime = 0.0;
        prime = (double)number / divide;
        if(dbg > 0){
            System.out.println("Debug number " + number + " | divide " + divide + " |prime : "  + prime + " | Math.abs(prime) " + Math.abs(prime));
        }
        if (prime == ((long)prime))//whats the best way to do this?
        {
            //divided evenly
            return divide;
        }
        else{
            return testPrime(number, divide - 2);
        }
    }
}

答案 4 :(得分:-1)

  

我的递归函数就像 - 如果我错了就纠正我。谢谢你。声明&gt;布尔b = isPrime(数字,数字-1);   递归函数 -

void isPrime(int p,int d);
{
int prime=p%d;
if((p==0&&d>1)||p%2==0)
return true;//that the number is not prime
if(d==1)
return false;
else
return isPrime(p,d-2);//calls the function again
}

答案 5 :(得分:-1)

好吧,我直接给你所有的代码,而不是写代码片段。希望你们都喜欢这个,因为我尽力使它变得尽可能简单。 代码是:&gt;

import java.util.*;
class Prime_Number
{
    static int c=0;
    public static void main(String args[])
    {
        int n,i,sq=0;
        Scanner in=new Scanner(System.in);
        Prime_Number ob=new Prime_Number();
        System.out.print("Enter a no.:>");
        n=in.nextInt();
        i=n;
        sq=(int)(Math.sqrt(n));//square root is been taken since a no. cannot have factors greater than its square root
        int k=ob.prime_Chk(n,i,sq);
           if(k==1)
              {
                 System.out.println("Prime");
              }
                 else
                     {
                       System.out.println("Non-Prime");
                      }
      }
public int prime_Chk(int g,int i,int sq)
    {
        if(i==sq)
        {
            return c;
        }
        else
        {
            if(g%i==0)
            {
                c++;
            }
            i--;
            return(prime_Chk(g,i,sq));
        }
    }
}

在prime()中我把int i,int sq和int g作为参数。如果你愿意,那么你也可以使用其他变量。

答案 6 :(得分:-1)

import java.util.Scanner;

public class HW8R_T03 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number: ");
        int n = sc.nextInt();
        int simple = prime(n,n-1);
        System.out.println(simple==1 ? "prime" : "not prime");

    }

    static int prime(int x, int y){
        int div = 1;
        if (y==0 || y==1){
             return div;
        }
        if (x%y==0){
            div = y;
        } else {
            div = prime (x, --y);
        }
        return div;
    }


}