Advertisement
v_ignatyev

An example of optimization of Javascript loop

Jan 15th, 2013
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. // Finding divisors in Javascript
  3. // An example of optimization of Javascript loop
  4. //
  5.  
  6.  
  7. // this runs in 1317 ms for n=1E8
  8. function divisors_count_slow ( n ) {// 1E8 -> 1317ms
  9.   if (n == 1) return 1;
  10.   i = 1;
  11.   count = 0;
  12.   p = 0;
  13.   n2 = n/2;
  14.   while (i < n2 + 1 && p != i) {
  15.     d = n / i;
  16.     if (d % 1.0 == 0) {
  17.       count+=2;
  18.       p = d;
  19.     }
  20.     i++;
  21.   }
  22.   return count;
  23. }
  24.  
  25. // runs in 1246 ms for n=1E8
  26. function divisors_count_faster ( n ) {
  27.   if (n == 1) return 1;
  28.   i = 1;
  29.   count = 0;
  30.   p = 0;
  31.   while (i < n / 2 + 1 && p != i) {
  32.     d = n / i;
  33.     if (d % 1.0 == 0) {
  34.       count+=2;
  35.       p = d;
  36.     }
  37.     i++;
  38.   }
  39.   return count;
  40. }
  41.  
  42. // this runs in 580 ms for n=1E8
  43. function divisors_count (n) {
  44.   if (n == 1) return 1;
  45.   i = 1;
  46.   count = 0;
  47.   p = 0;
  48.   while (i < n / 2 + 1 && p != i) {
  49.     d = n % i;
  50.     if (d == 0) {
  51.       count+=2;
  52.       p = n/i;
  53.     }
  54.     i++;
  55.   }
  56.   return count;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement