质数检查Java

时间:2019-02-12 04:54:26

标签: java numbers

编写一个程序以读取n个数字。指定为输入的第一个数字为n。接下来,程序应读取n个整数。

程序应检查每个数字是否为质数以及其反数是否为质数。

以升序显示所有此类数字。

请考虑以下输入和输出示例:

输入: 7 11 12 23 19 7 113 101

输出:

7 11 101 113

我的代码

public class Prime {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        int temp;

        int[] a = new int [x];
        int[] r = new int [x];
        int[]c = new int[a.length+r.length];
        int[] rev = new int [x];

        for(int i=0;i<x;i++){
            a[i] = sc.nextInt();
            rev[i]=a[i];
        }

        for(int i = 0; i < a.length; i++) {
            while(rev[i] != 0) {
                r[i] = r[i] * 10;
                r[i] = r[i] + rev[i]%10;
                rev[i] = rev[i]/10;
            }
        }

        for(int i = 0; i < a.length; i++) {
            boolean isPrime = true;
            for (int j = 2; j < i; j++) {
                if((a[i]%j==0) || (r[i]%j==0)) {
                    isPrime = false;
                    break;
                }
            }
            if(isPrime) 
                System.out.println(a[i]);
            System.out.println(r[i]);
        }
    }
}

在某个地方我卡住了,我不知道如何消除重复的否,最后如何合并数组,并且当我输入input和2时它会打印1和2为质数。

5 个答案:

答案 0 :(得分:2)

您可以尝试以下代码。希望对您有帮助,

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class PrimeNumberTest {
    public static void main(String[] args) {
         List<Integer> list = new ArrayList<>(Arrays.asList(7, 11, 12, 23, 19, 7 ,113, 101)); 
         //To remove duplicates
         Set<Integer> set = new TreeSet<>(list);
         System.out.println(getPrimeNumbers(set).toString().replaceAll(",", "").replace("]", "").replace("[", ""));
    }
    //Method to get unique ordered set of prime numbers
    private static Set<Integer> getPrimeNumbers(Set<Integer> set) {
        Set<Integer> resultList=new TreeSet<>();
        set.forEach(ele->{
            //check for prime
            if(isPrime(ele)){
                //if prime number check for reverse and if true, add to result
                 if(isPrime(reverserNumb(ele)))
                     resultList.add(ele);
            }
        });
        return resultList;
    }

    private static boolean isPrime(int num){
        if(num<2)
            return false;
        // Check for even numbers
        if (num % 2 == 0) {
            return num == 2;
        }
      // Check for odd numbers
        for (int i = 3; i*i <= num; i += 2) {
            if (num % i == 0) {
                return false;
            }
        }

        return true;
    }
    private static int reverserNumb(int num) {
        return Integer.valueOf(new StringBuilder(String.valueOf(num)).reverse().toString());
    }
}

答案 1 :(得分:1)

您需要使用TreeSet-它仅包含不同的元素并以排序形式给出结果。您可以参考以下代码-

  Set<Integer> set = new TreeSet<>();
            for(int i = 0; i < a.length; i++) {
                boolean isPrime = true;
                if(isPrime(a[i]) && isPrime(r[i]))
                    set.add(a[i]);
            }
Iterator it = set.iterator();
        while(it.hasNext())
            System.out.print(it.next() + " ");

还创建了一个用于检查质数的函数-

private static boolean isPrime(int num) {
        if(num==1) return false;
        for(int i = 2; i <= num/2; ++i)
        {
            if(num % i == 0)
            {
               return false;
            }
        }
        return true;
    }

答案 2 :(得分:0)

以下是使用√n方法进行主要测试的代码

static boolean isPrime(int n){
//corner case
if (n <= 1) return false; 
if (n <= 3) return true; 
//middle 5 number
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6) 
            if (n % i == 0 || n % (i + 2) == 0) 
            return false;  
return true;
}

使用可以使用set删除重复元素

答案 3 :(得分:0)

尝试该代码是否有效,希望对您有所帮助

代码:

        import java.util.ArrayList;
        import java.util.Collections;
        import java.util.Scanner;

        public class PrimeNumbers {

            static ArrayList<Integer> prime = new ArrayList<>(); 
            public static void main(String[] args) {
                Scanner user_input = new Scanner(System.in);
                System.out.print("Enter Number of Integers: ");
                int number_count = user_input.nextInt();
                int[] numbers = new int[number_count];
                for (int i = 0; i < numbers.length; i++) {
                    System.out.print("Enter Integer: ");
                    numbers[i] = user_input.nextInt();
                }

                System.out.print("Values Entered: ");
                for (int i = 0; i < numbers.length; i++) {
                    System.out.print(numbers[i] + " ");
                    checkPrime(numbers[i],false); //false don't reverse
                    checkPrime(numbers[i],true); //true reverse value to check if it is also prime
                }

                System.out.print("\nList of prime numbers: ");
                Collections.sort(prime);
                for(int n : prime){
                    System.out.print(n + " ");
                }
                if(prime.isEmpty()){
                    System.out.print("no prime numbers on list\n");
                }
            }

            //check for duplicates
            static void insertValueToPrime(int n){
                for(int p : prime){
                    if(n == p){
                        return;
                    }
                }
                prime.add(n);
            }


            static void checkPrime(int n,boolean isReverse) {
                int i, m = 0, flag = 0,realn = n;
                if(isReverse){
                    n = reverseNumber(n);
                }
                m = n / 2;
                if (n == 0 || n == 1) {
                    //no a prime number
                } else {
                    for (i = 2; i <= m; i++) {
                        if (n % i == 0) {
        //                    not a prime number
                            flag = 1;
                            break;
                        }
                    }
                    if (flag == 0) {
                        insertValueToPrime(realn);
                    }
                }
            }

            static int reverseNumber(int n){
                String reverse = "",str=""+n;
                for(int i = str.length() - 1; i >= 0; i--)
                {
                    reverse = reverse + str.charAt(i);
                }
                return Integer.parseInt(reverse);
            }

        }

答案 4 :(得分:-1)

您可以在Java 8中使用Stream.distinct() 只需将您的数组传递到数组列表并使用.distinct()

删除其重复项
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 
import java.util.stream.Collectors; 

        //list with duplicates 
        List<Integer> list = new ArrayList<>( 
            Arrays.asList(3, 10, 3, 3, 4, 5, 5)); 
        //new list without duplicates
        List<Integer> newList = list.stream() 
                                      .distinct() 
                                      .collect(Collectors.toList());