Problem:
Design and implement an algorithm to establish all the primes in the first n positive integers.
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FindThePrimeNumber2 {
List<Integer> resultList = new ArrayList<Integer>();
int n;
public static void main(String[] args) {
FindThePrimeNumber2 findThePrimeNumber2 = new FindThePrimeNumber2();
findThePrimeNumber2.getTheNumber();
findThePrimeNumber2.findPrimeNumbers();
findThePrimeNumber2.printTheResult();
}
public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("Enter number : ");
n = s.nextInt();
s.close();
}
public void findPrimeNumbers(){
for (int i = 2; i < n; i++) {
if(isPrime(i)){
resultList.add(i);
}
}
}
public boolean isPrime(int i){
for(int j = 2; j<= Math.sqrt(i); j++){
if(i%j == 0){
return false;
}
}
return true;
}
public void printTheResult(){
System.out.println("the prime numbers upto given number are " + resultList);
}
}
Output:
Enter number :
20
the prime numbers upto given number are [2, 3, 5, 7, 11, 13, 17, 19]
Design and implement an algorithm to establish all the primes in the first n positive integers.
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FindThePrimeNumber2 {
List<Integer> resultList = new ArrayList<Integer>();
int n;
public static void main(String[] args) {
FindThePrimeNumber2 findThePrimeNumber2 = new FindThePrimeNumber2();
findThePrimeNumber2.getTheNumber();
findThePrimeNumber2.findPrimeNumbers();
findThePrimeNumber2.printTheResult();
}
public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("Enter number : ");
n = s.nextInt();
s.close();
}
public void findPrimeNumbers(){
for (int i = 2; i < n; i++) {
if(isPrime(i)){
resultList.add(i);
}
}
}
public boolean isPrime(int i){
for(int j = 2; j<= Math.sqrt(i); j++){
if(i%j == 0){
return false;
}
}
return true;
}
public void printTheResult(){
System.out.println("the prime numbers upto given number are " + resultList);
}
}
Output:
Enter number :
20
the prime numbers upto given number are [2, 3, 5, 7, 11, 13, 17, 19]
Enter number :
10
the prime numbers upto given number are [2, 3, 5, 7]
No comments:
Post a Comment