简体   繁体   English

使用递归在Java中打印质数

[英]Printing prime numbers in Java using recursion

I wrote a similar function in C, and was able to achieve the required result unlike java. 我用C语言编写了一个类似的函数,与java不同,它能够实现所需的结果。 Below is the code, which checks if a number is prime recursively. 下面是代码,用于检查数字是否为素数。 Compilation says, i'm missing a return statement. 编译说,我丢失了一个return语句。 The number to be checked if a prime is x. 要检查素数为x的数字。 The variable i is the divisor.(ie) x/2, (x/2)-1,...0. 变量i是除数。(即x / 2,(x / 2)-1,... 0。

public int primes(int x, int i)
{
    if(i==0)
        return 1;
    if(x%i==0)
        return 0;
    else
        primes(x, i-1);
}

What is the complexity of this code if I had to print the first 1000 prime numbers. 如果必须打印前1000个素数,此代码的复杂性是多少?

In this case: 在这种情况下:

else
    primes(x, i-1);

You aren't returning anything. 你什么也没退。 However, the compiler must ensure that something is returned in all cases. 但是,编译器必须确保在所有情况下都返回某些内容。 Just return whatever the recursive method call returns: 只要返回任何递归方法调用返回的内容:

else
    return primes(x, i-1);

Also, modify the first case's condition to i == 1 so it returns 1 on primes correctly. 同样,将第一种情况的条件修改为i == 1这样它就可以正确返回素数为1

At first glance, it appears that you're missing a return in your else statement: 乍一看,您似乎在else语句中缺少返回值:

public int primes(int x, int i)
{
    if(i==1)
        return 1;
    if(x%i==0)
        return 0;
    else
        return primes(x, i-1);
}

edit: Also, as said in rgettman's answer, there is a logical bug in the first conditional if(i==0) . 编辑:另外,正如rgettman的回答中所述,第一个条件if(i==0)存在逻辑错误。 It should be if(i==1) . 应该是if(i==1) After testing the code with the above edit here is my result: 用上面的编辑测试代码后,这是我的结果:

List of primes under 100: 
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

You just need a return inside your else . 您只需要在自己的else内部return

else
    return primes(x, i-1);

The return there will return the results of the recursive calls, and they'll work their way up the stack. 那里的return将返回递归调用的结果,它们将沿着堆栈的方式工作。 Though, this might lead to StackOverflowException s. 但是,这可能会导致StackOverflowException

You can apply the logic as: 您可以将逻辑应用为:

for (i = 1; i <= 100; i++) {              
    int counter=0;    
    for (num = i; num>=1; num--) {
        if (i%num==0) {
            counter = counter + 1;
        }
    }
    if (counter == 2) {
        //Appended the Prime number to the String
        primeNumbers = primeNumbers + i + " ";
    }   
}

Then display primeNumbers . 然后显示primeNumbers

import java.util.Scanner;

public class Primenumm {
     public static void main(String[] args) {
          System.out.println("Enter the Number :-");
          Scanner s = new Scanner(System.in);
          int limit = s.nextInt();
          for (int i = limit; i >= 1; i--) {
               if (primes(i, i - 1) == 1) {
                    System.out.println(i + " is a prime no");
               } else {
                    System.out.println(i + " is not a prime no");
               }
          }
     }

     private static int primes(int x, int i) {
          if (i == 1) {
               return 1;
          }
          try {
               if (x % i == 0) {
                    return 0;
               } else {
                    return primes(x, i - 1);
               }
          } catch (Exception e) {
               return 1;
          }
     }
}
public class PrintPrime {

    public static void main(String args[]) {
        for (int i = 2; i < 1000; i++) {
            primes(i, Math.ceil(Math.sqrt(i)));

        }
    }

    public static int primes(int x, double i) {
        if (i == 1)
            System.out.println(x);
        if (x % i == 0)
            return 0;
        else
            return primes(x, i - 1);
    }

}
import java.util.Scanner;
public class Primenumm {

static int limit,flag;

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

    System.out.println("Enter the Number :-");
    Scanner s=new Scanner(System.in);
    limit=s.nextInt();
    int i=0,j=limit;
    printNum(i,j);
}

private static int  printNum(int i, int j) {
    // TODO Auto-generated method stub

    if(j==0){
        return 1;
    }
    if(i%j==0){
        return  0;
    }
    else{

        return  printNum(i,j-1);
    }
}

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

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