java code to print alternate prime numbers in reverse order -
the following java code print 'n' prime no.s want modify such can print alternate prime numbers in reverse order.
import java.util.scanner; class primenumberdemo { public static void main(string args[]) { int n; int status = 1; int num = 3; //for capturing value of n scanner scanner = new scanner(system.in); system.out.println("enter value of n:"); //the entered value stored in var n n = scanner.nextint(); if (n >= 1) { system.out.println("first "+n+" prime numbers are:"); //2 known prime number system.out.println(2); } ( int = 2 ; <=n ; ) { ( int j = 2 ; j <= math.sqrt(num) ; j++ ) { if ( num%j == 0 ) { status = 0; break; } } if ( status != 0 ) { system.out.println(num); i++; } status = 1; num++; } } }
as per code have made modification , below how achieve alternate prime numbers in reverse order
public static void main(string args[]) { int n; int status = 1; int num = 3; list<integer> primenumberlist=new arraylist<integer>(); //for capturing value of n scanner scanner = new scanner(system.in); system.out.println("enter value of n:"); //the entered value stored in var n n = scanner.nextint(); if (n >= 1) { system.out.println("first "+n+" prime numbers are:"); //2 known prime number system.out.println(2); primenumberlist.add(2); } ( int = 2 ; <=n ; ) { ( int j = 2 ; j <= math.sqrt(num) ; j++ ) { if ( num%j == 0 ) { status = 0; break; } } if ( status != 0 ) { system.out.println(num); primenumberlist.add(num); i++; } status = 1; num++; } //reversing collection collections.reverse(primenumberlist); system.out.println("\n"); system.out.println("alternate prime numbers in reverse order \n"); for(int k=0;k<primenumberlist.size();k++){ if((k%2)==0) system.out.println(""+primenumberlist.get(k)); }
}
result output
enter value of n: 10 first 10 prime numbers are: 2 3 5 7 11 13 17 19 23 29 alternate prime numbers in reverse order 29 19 13 7 3