fork(2) download
  1. class Main {
  2. public static void main(String[] args) {
  3.  
  4. //Case 1 comparing Algorithms
  5. long startTime = System.currentTimeMillis(); // Start Time
  6. for (int i = 2; i <= 100000; ++i){
  7. if (isPrime1(i)) continue;
  8. }
  9. long stopTime = System.currentTimeMillis(); // End Time
  10. System.out.printf("Duracion: %4d ms. while (i*i <= N) Algorithm\n", stopTime - startTime);
  11.  
  12. //Case 2 comparing Algorithms
  13. startTime = System.currentTimeMillis();
  14. for (int i = 2; i <= 100000; ++i){
  15. if (isPrime2(i)) continue;
  16. }
  17. stopTime = System.currentTimeMillis();
  18. System.out.printf("Duracion: %4d ms. while (i <= sqrt(N)) Algorithm\n", stopTime - startTime);
  19.  
  20. //Case 3 comparing Algorithms
  21. startTime = System.currentTimeMillis();
  22. for (int i = 2; i <= 100000; ++i){
  23. if (isPrime3(i)) continue;
  24. }
  25. stopTime = System.currentTimeMillis();
  26. System.out.printf("Duracion: %4d ms. s = sqrt(N) while (i <= s) Algorithm\n", stopTime - startTime);
  27.  
  28. //Case 4 comparing Algorithms
  29. startTime = System.currentTimeMillis();
  30. for (int i = 2; i <= 100000; ++i){
  31. if (isPrime4(i)) continue;
  32. }
  33. stopTime = System.currentTimeMillis();
  34. System.out.printf("Duracion: %4d ms. s = Math.sqrt(N) while (i <= s) Algorithm\n", stopTime - startTime);
  35.  
  36. }
  37.  
  38. public static boolean isPrime1(int n)
  39. {
  40. for (long i = 2; i*i <= n; i++){
  41. if (n%i==0)
  42. return false;
  43. }
  44. return true;
  45. }
  46.  
  47. public static boolean isPrime2(int n)
  48. {
  49. for (long i = 2; i <= sqrt(n); i++){
  50. if (n%i==0)
  51. return false;
  52. }
  53. return true;
  54. }
  55.  
  56. public static boolean isPrime3(int n)
  57. {
  58. double s = sqrt(n);
  59. for (long i = 2; i <= s; i++){
  60. if (n%i==0)
  61. return false;
  62. }
  63. return true;
  64. }
  65. public static boolean isPrime4(int n)
  66. {
  67. //Proving wich if faster between my sqrt method or Java's sqrt
  68. double s = Math.sqrt(n);
  69. for (long i = 2; i <= s; i++){
  70. if (n%i==0)
  71. return false;
  72. }
  73. return true;
  74. }
  75. public static double abs(double n){
  76. return n < 0 ? -n : n;
  77. }
  78. public static double sqrt(double n)
  79. {
  80. //Newton's method, from book Algorithms 4th edition by Robert Sedgwick and Kevin Wayne
  81. if (n < 0) return Double.NaN;
  82.  
  83. double err = 1e-15;
  84. double p = n;
  85.  
  86. while (abs(p - n/p) > err * n)
  87. p = (p + n/p) / 2.0;
  88.  
  89. return p;
  90. }
  91. }
Success #stdin #stdout 1.42s 380352KB
stdin
Standard input is empty
stdout
Duracion:  106 ms. while (i*i <= N) Algorithm
Duracion:  943 ms. while (i <= sqrt(N)) Algorithm
Duracion:  164 ms. s = sqrt(N) while (i <= s) Algorithm
Duracion:  131 ms. s = Math.sqrt(N) while (i <= s) Algorithm