5. Make shell function which can find the last three prime number lesser than 100. code example

Example: generate all prime number less than n java

/**
Author: Jeffrey Huang
As far as I know this is almost the fastest method in java
for generating prime numbers less than n.
A way to make it faster would be to implement Math.sqrt(i)
instead of i/2.

I don't know if you could implement sieve of eratosthenes in 
this, but if you could, then it would be even faster.

If you have any improvements please email me at
[email protected].
 */


import java.util.*;
 
public class Primecounter {
    
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
      //int i =0;
      int num =0;
      //Empty String
      String  primeNumbers = "";
      boolean isPrime = true;
      System.out.print("Enter the value of n: ");
      System.out.println();
      int n = scanner.nextInt();

      for (int i = 2; i < n; i++) {
         isPrime = true;
         for (int j = 2; j <= i/2; j++) {
            if (i%j == 0) {
               isPrime = false; 
            }
         }
         if (isPrime)
         System.out.print(" " + i);
      }	

    }
}

Tags:

Java Example