Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- this program finds prime numbers and puts them in a list.
- for the sake of interactivity, it doesn't use an array so it can expand on size as it goes.
- it is hardcoded not to allow first value to be less than one, i.e 0 or any negative becomes 1.
- The algorithm works as follows:
- First, it makes sure it isn't a 1. I made it separate if to make calculation/syntax easier.
- Else, it goes through every int between 2 and square root of passed int (everything between low and high inclusive).
- Reason: n is a prime if it's not divisible by previous primes/factors. Reaching its sqrt means we reach the point where it's divisible by itself.
- Next numbers will be factors of previously checked ones.
- On my machine, it takes 2.490190249 seconds to find primes between 1 to 100. IS THAT FAST ENOUGH FOR YOU HACKERRANK?
- */
- import java.util.*;
- import java.lang.*;
- public class primenumfinder{
- public static void main(String args[]){
- long startTime = System.nanoTime();
- Scanner sc = new Scanner(System.in);
- System.out.print("Enter lower end of range:");
- int low = sc.nextInt();
- if(low<1){
- low = 1;
- }
- System.out.print("Enter higher end of range:");
- int high = sc.nextInt();
- List primes = new ArrayList();
- for(int i=low;i<high;i++){
- if(findPrime(i)){
- primes.add(i);
- }
- }
- for(int i=0;i<primes.size();i++){
- System.out.println(primes.get(i));
- }
- long endTime = System.nanoTime();
- long totalTime = endTime - startTime;
- System.out.println(totalTime);
- }
- public static boolean findPrime(int n){
- if(n == 1){
- return true;
- }
- else{
- for(int i=2;i<(int)Math.sqrt(n);i++){
- if(n%i == 0){
- return false;
- }
- }
- return true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement