Saturday, March 14, 2020

isPrime recursive


#include <iostream>
using namespace std;

int increments[] = { 2, 4 };

// Already beyond the square root? -> true (prime)
// (else)
// Divisible by current divisor?   -> false (not prime)
// (else)
// Calculate next divisor and recurse
bool isPrime(int n, int divisor, int incr) {
   return (divisor * divisor > n ) || 
          ( (n % divisor != 0) && 
            isPrime(n, divisor + incr, increments[incr == 2] )
          );
}
 
bool isPrime(int n) {
    return isPrime(n, 2, 1);
}

int main()
{
    for(int i = 2; i <= 100; i++ ) {
        if( isPrime(i) ) {
            cout << i << " ";
        }
    }
    cout << endl;

    return 0;
}

Other entries:

Sunday, March 1, 2020

Generate random numbers without repetition

Instead of controlling the repetition by inserting the already-generated-number in a set, create the set first, pick from there, and remove it for the next iteration,

e.g.:


import java.util.Random;

public class ControlRepetitionWithoutKeepingScore {

     public static void main(String []args) {

         int choices[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
         int sz = choices.length;
         Random random = new Random();
         
         for(int i = 0; i < choices.length; i++ ) {
             int pos = random.nextInt(sz);
             print(choices[pos]);
             
             choices[pos] = choices[sz-1];
             sz--;
         }
     }
}


Other entries:

Sunday, February 16, 2020

Shuffle characters in a String (java)

Converts chars to List --> Collections.shuffle --> String.join



import java.util.Collections;
import java.util.List;
import java.util.Arrays;

public class Shuffler {

     public static void main(String []args){
        String s = "012345";
        
        for( int i = 0; i < 10; i++) {
           System.out.println(shuffle(s));
        }
     }
     
     public static String shuffle(String s) {
        List<String> chars = Arrays.asList(s.split(""));
        Collections.shuffle(chars);
        return String.join("", chars);
     }
}

Monday, August 5, 2019

isPrime, optimization 4

Check every number and keep the previosly generated primes. Use them to test the following numbers.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const int PSIZE = 150000;
int primes[PSIZE];
int sz = 0;

bool isPrime4( int x ) {
  if(x < 2) return true;

  int limit = (int) sqrt(x);
  primes[sz] = limit+1;
  for(int *p = primes; *p <= limit; p++) {
      if( x % *p == 0 ) {
          return false;
      }
  }
  assert(sz < PSIZE);
  primes[sz++] = x;
     
  return true;
}


Other entries:

isPrime, optimization 3

Divisors start in 5. Skip the divisors that are multiple of 2 or 3.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
bool isPrime3( int x ) {
  if( x == 2 || x == 3) {
      return true;
  }
  
  if( x % 2 == 0 || x % 3 == 0 ) {
      return false;
  }

  int divisor = 5;
  int delta = 2;
  int limit = (int) sqrt(x);
  while( divisor <= limit ) {
        if( x % divisor == 0 ) { 
            return false;
        }
        divisor += delta;
        delta = 6 - delta;
  }
  return true;
}


Other entries:

isPrime, optimization 1

It is not necessary to check divisors bigger than the square root of the number.

1
2
3
4
5
6
7
8
9
bool isPrime1( int x ) {
  int limit = (int) sqrt(x);
  for( int divisor = 2; divisor <= limit; divisor++ ) {
        if( x % divisor == 0 ) { 
            return false;
        }
  }
  return true;
}

isPrime, optimization 2

Only divide by odd numbers, until the square root of the number.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
bool isPrime2( int x ) {
  if( x == 2 ) {
      return true;
  }
  if( x % 2 == 0 ) {
      return false;
  }

  int limit = (int) sqrt(x);
  for( int divisor = 3; divisor <= limit; divisor += 2 ) {
        if( x % divisor == 0 ) { 
            return false;
        }
  }
  return true;
}


Other entries: