Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. /*
  2. this program finds prime numbers and puts them in a list.
  3. for the sake of interactivity, it doesn't use an array so it can expand on size as it goes.
  4. it is hardcoded not to allow first value to be less than one, i.e 0 or any negative becomes 1.
  5. The algorithm works as follows:
  6. First, it makes sure it isn't a 1. I made it separate if to make calculation/syntax easier.
  7. Else, it goes through every int between 2 and square root of passed int (everything between low and high inclusive).
  8. 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.
  9. Next numbers will be factors of previously checked ones.
  10. On my machine, it takes 2.490190249 seconds to find primes between 1 to 100. IS THAT FAST ENOUGH FOR YOU HACKERRANK?
  11. */
  12. import java.util.*;
  13. import java.lang.*;
  14. public class primenumfinder{
  15.     public static void main(String args[]){
  16.         long startTime = System.nanoTime();
  17.         Scanner sc = new Scanner(System.in);
  18.         System.out.print("Enter lower end of range:");
  19.         int low = sc.nextInt();
  20.         if(low<1){
  21.             low = 1;
  22.         }
  23.         System.out.print("Enter higher end of range:");
  24.         int high = sc.nextInt();
  25.         List primes = new ArrayList();
  26.         for(int i=low;i<high;i++){
  27.             if(findPrime(i)){
  28.                 primes.add(i);
  29.             }
  30.         }
  31.         for(int i=0;i<primes.size();i++){
  32.             System.out.println(primes.get(i));
  33.         }
  34.         long endTime   = System.nanoTime();
  35.         long totalTime = endTime - startTime;
  36.         System.out.println(totalTime);
  37.     }
  38.     public static boolean findPrime(int n){
  39.         if(n == 1){
  40.             return true;
  41.         }
  42.         else{
  43.             for(int i=2;i<(int)Math.sqrt(n);i++){
  44.                 if(n%i == 0){
  45.                     return false;
  46.                 }
  47.             }
  48.             return true;
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement