Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Optimize array to store 1 or 0 for whether the number is prime, since…

… there's a loop that already has the number itself
  • Loading branch information...
commit 09661e69d05aad92ee79b3a01c06b5197c37488c 1 parent d340b0d
Joshua Clayton authored September 12, 2010

Showing 1 changed file with 9 additions and 8 deletions. Show diff stats Hide diff stats

  1. 17  ext/sieve/sieve.c
17  ext/sieve/sieve.c
@@ -11,34 +11,35 @@ void Init_sieve() {
11 11
 
12 12
 static VALUE sieve(const VALUE self) {
13 13
   if(NUM2LONG(self) < 2) { return Qnil; }
14  
-  long number = NUM2LONG(self) + 1,
15  
-     * numbers = malloc(number * sizeof(long));
  14
+  long number = NUM2LONG(self) + 1;
  15
+  short* numbers = malloc(number * sizeof(short));
16 16
 
17 17
   if(numbers == NULL) {
18 18
     rb_raise(rb_eNoMemError, "Can't allocate enough memory.");
19 19
   }
20 20
 
21  
-  numbers[0] = numbers[1] = -1;
  21
+  numbers[0] = numbers[1] = 0;
22 22
   long i;
23  
-  for(i = 2; i < number; i++) { numbers[i] = i; }
  23
+  for(i = 2; i < number; i++) { numbers[i] = 1; }
24 24
 
25 25
   long current_square;
26 26
   for(i = 0; i < number; i++) {
27  
-    if(numbers[i] == -1) { continue; }
  27
+    if(numbers[i] == 0) { continue; }
28 28
 
29 29
     current_square = powl(i, 2);
30 30
     if(current_square > number) { break; }
31 31
 
32 32
     long n;
33 33
     for(n = current_square; n < number; n += i) {
34  
-      numbers[n] = -1;
  34
+      numbers[n] = 0;
35 35
     }
36 36
   }
37 37
 
38 38
   VALUE primes_array = rb_ary_new();
39 39
   for(i = 0; i < number; i++) {
40  
-    if(numbers[i] == -1) { continue; }
41  
-    rb_ary_push(primes_array, LONG2FIX(numbers[i]));
  40
+    if(numbers[i] == 1) {
  41
+      rb_ary_push(primes_array, LONG2FIX(i));
  42
+    }
42 43
   }
43 44
 
44 45
   free(numbers);

0 notes on commit 09661e6

Please sign in to comment.
Something went wrong with that request. Please try again.