Prime number check java

user11048808 :

Write a program to read n numbers. The first number specified as input will be n. Next, the program should read n integer numbers.

The program should check for each number if it is prime as well as if its reverse is prime.

Display all such numbers in ascending order.

Consider below example for input and output:

Input: 7 11 12 23 19 7 113 101

Output:

7 11 101 113

My code

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]);
        }
    }
}

Somewhere I am stuck I don't know how to eliminate repeated no, how to merge the array at last and also it is printing 1 and 2 as prime no when I give input and 2

p.bansal :

You need to use TreeSet - which will contain only distinct elements and give result in sorted form. You can refer to following code-

  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() + " ");

Also create a function for checking prime numbers -

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;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=78888&siteId=1