QuestionAsk Questions?

i want to write a code in java that picks prime numbers from an existing list regardless how long the list is, it should then select non prime numbers when prime numbers are finished

View Answers

May 10, 2010 at 1:20 PM

Hi Friend,

Try the following code:

import java.util.*;

class PickNumbersFromList{

static boolean isPrime(int number){

boolean isPrime=false;

int i=(int) Math.ceil(Math.sqrt(number));

while (i>1){

if ((number!=i) && (number%i==0)){

isPrime=false;

break;

}

else if (!isPrime)

isPrime=true;

--i;

}

return isPrime;

}

public static void main(String[] args) {

ArrayList<Integer> list=new ArrayList<Integer>();

list.add(1);

list.add(2);

list.add(3);

list.add(4);

list.add(5);

list.add(6);

list.add(7);

list.add(8);

list.add(9);

list.add(10);

Integer array[] = new Integer[list.size()];

array = list.toArray(array);

System.out.println("Prime Numbers are: ");

for(int i=0;i<array.length;i++){

if(isPrime(array[i])){

System.out.println(array[i]);

}

}

System.out.println("Non Prime Numbers are: ");

for(int i=0;i<array.length;i++){

if(!isPrime(array[i])){

System.out.println(array[i]);

}

}

}

}

Thanks

Try the following code:

import java.util.*;

class PickNumbersFromList{

static boolean isPrime(int number){

boolean isPrime=false;

int i=(int) Math.ceil(Math.sqrt(number));

while (i>1){

if ((number!=i) && (number%i==0)){

isPrime=false;

break;

}

else if (!isPrime)

isPrime=true;

--i;

}

return isPrime;

}

public static void main(String[] args) {

ArrayList<Integer> list=new ArrayList<Integer>();

list.add(1);

list.add(2);

list.add(3);

list.add(4);

list.add(5);

list.add(6);

list.add(7);

list.add(8);

list.add(9);

list.add(10);

Integer array[] = new Integer[list.size()];

array = list.toArray(array);

System.out.println("Prime Numbers are: ");

for(int i=0;i<array.length;i++){

if(isPrime(array[i])){

System.out.println(array[i]);

}

}

System.out.println("Non Prime Numbers are: ");

for(int i=0;i<array.length;i++){

if(!isPrime(array[i])){

System.out.println(array[i]);

}

}

}

}

Thanks

Related Tutorials/Questions & Answers:

Advertisements