Tuesday, April 2, 2013

Java: Prime Number List

/*
Please implement this method to
return a list of all prime numbers in the given range (inclusively).
A prime number is a natural number that has exactly two distinct natural number divisors, which are 1 and the prime number itself.
The first prime numbers are: 2, 3, 5, 7, 11, 13
*/

 

  1. import java.util.List;

  2. import java.util.ArrayList;


  3. public class PrimeNumber {

  4. /**

  5. * @param args

  6. */

  7. public static void main(String[] args) {

  8. // TODO Auto-generated method stub

  9. System.out.println(getPrimeNumbers(481,500));

  10. }

  11. public static List<Integer> getPrimeNumbers(int from, int to) {

  12. /*

  13. Please implement this method to

  14. return a list of all prime numbers in the given range (inclusively).

  15. A prime number is a natural number that has exactly two distinct natural number divisors, which are 1 and the prime number itself.

  16. The first prime numbers are: 2, 3, 5, 7, 11, 13

  17. */


  18. List<Integer> list = new ArrayList<Integer>();

  19. boolean b=false;

  20. for(int j=from;j<=to;j++)

  21. {

  22. b=false;

  23. System.out.println("from "+from);

  24. int i=2;

  25. for(;i<j/2;i++)

  26. {


  27. if(j%i==0)

  28. {

  29. b=true;

  30. break;

  31. }



  32. }

  33. System.out.println("j= "+j);

  34. System.out.println("b= "+b);

  35. if(b==false && j!=1 && j!=0)

  36. list.add(j);


  37. }


  38. System.out.println(list);

  39. return list;

  40. }

  41. }


 

Download Link: Click Here

0 comments: