In: Computer Science
The variable x takes the values from 1 to 100, with these values, create two lists, one where the prime numbers are stored in one, and another where the non-prime numbers are stored, indicate and print the result
Code:
import java.util.*;
class Main{
public static boolean CheckPrime(int n) {
for (int i = 2; i <= n / 2; i++) {
if ((n % i) == 0) { //ckeck number is divisible by any previous numbers
return false; //if divisible then ite not prime then return false
}
}
return true; //if number is not divisible by any previous numbers then its prime number so return true
}
public static void main(String args[]){
int[] x = new int[100]; //initialize x variable to store 1 to 100 numbers
boolean isPrime;
ArrayList<Integer> prime=new ArrayList<Integer>(); //list to store prime numbers
ArrayList<Integer> nonprime=new ArrayList<Integer>(); //list to store non prime numbers
for (int i = 0; i < 100; i++) { //store 1 to 100 numbers in x variable
x[i]=i+1;
}
for (int i = 0; i < 100; i++) { //Iterate 1 to 100 numbers
isPrime = CheckPrime(x[i]); //call function to check number is prime or not
if (isPrime) //if number is prime number
prime.add(x[i]); //then store in prime list
else
nonprime.add(x[i]); //otherwise store in nonprime list
}
System.out.println("Prime numbers between 1 to 100:\n"+prime); //print list of prime numbes
System.out.println("\nNon-Prime numbers between 1 to 100:\n"+nonprime); //print list of nonprime numbers
}
}
Output:
.