Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Finding divisors in Javascript
- // An example of optimization of Javascript loop
- //
- // this runs in 1317 ms for n=1E8
- function divisors_count_slow ( n ) {// 1E8 -> 1317ms
- if (n == 1) return 1;
- i = 1;
- count = 0;
- p = 0;
- n2 = n/2;
- while (i < n2 + 1 && p != i) {
- d = n / i;
- if (d % 1.0 == 0) {
- count+=2;
- p = d;
- }
- i++;
- }
- return count;
- }
- // runs in 1246 ms for n=1E8
- function divisors_count_faster ( n ) {
- if (n == 1) return 1;
- i = 1;
- count = 0;
- p = 0;
- while (i < n / 2 + 1 && p != i) {
- d = n / i;
- if (d % 1.0 == 0) {
- count+=2;
- p = d;
- }
- i++;
- }
- return count;
- }
- // this runs in 580 ms for n=1E8
- function divisors_count (n) {
- if (n == 1) return 1;
- i = 1;
- count = 0;
- p = 0;
- while (i < n / 2 + 1 && p != i) {
- d = n % i;
- if (d == 0) {
- count+=2;
- p = n/i;
- }
- i++;
- }
- return count;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement