Java程序打印素数直到用户输入

时间:2017-10-13 15:17:31

标签: java primes

到目前为止我有这个代码,但它没有给我正确的输入。它需要从2打印素数到用户输入的数量。我究竟做错了什么?

import java.util.Scanner; 
public class Exhibit2 {
    public static void main(String args[]) { //forgot to add main
        System.out.println("This program takes the user input and prints the prime numbers until that number");
        System.out.println ("Enter Number:");
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        for(int i=2;i<num;i++){
          for(int j=2; j<i; j++){
            if(num%j == 0){
              System.out.print(" ");
            }
            else{
              System.out.print(i);
            }
          }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我编写了一个程序,可以找到一定数量的素数和起始点。我刚才写过这篇文章,我确信有更好的方法 - 但它允许你选择一个起始编号并继续指定一个点。

public static void main(String[] args) {

    System.out.println("This program takes the user input and prints the prime numbers until that number");
    System.out.println ("Enter Number:");
    Scanner sc = new Scanner(System.in);
    num = sc.nextInt();

    long startValue = 0;
    long primeNumbersToTest = num;
    for (long i = startValue; i < primeNumbersToTest; i++) {
        if (findPrime(i).equals("Prime")) {
            System.out.println(i + " is Prime");
        } else {
            System.out.println(i + " is not Prime");
        }
    }
}

public static String findPrime(long num) {

    boolean isPrime = true;
    for (long i = 2; i <= num / i; i++) {
        if ((num % i) == 0) {
            isPrime = false;
            break;
        }
    }
    if (isPrime)
        return "Prime";
    else
        return "Not Prime";
}

它输出前10个如下:

0 is Prime
1 is Prime
2 is Prime
3 is Prime
4 is not Prime
5 is Prime
6 is not Prime
7 is Prime
8 is not Prime
9 is not Prime
10 is not Prime

答案 1 :(得分:0)

import java.util.Scanner; 

public class Main {
    public static void main(String args[]) { 
        System.out.println("This program takes the user input and prints the prime numbers until that number");
        System.out.println ("Enter Number:");
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();  
        int i = 0;
        while(i<=num) {
            if(isPrime(i)) {
                System.out.println("Prime Number: "+i);
            }
            i++;
        }    
    }

    public static boolean isPrime(int n) {
        if(n > 2 && (n & 1) == 0)
           return false;
        for(int i = 3; i * i <= n; i += 2)
            if (n % i == 0) 
                return false;
        return true;
    }
}

这将打印出从0到输入int的素数,速度不错。