Famously, addition and negation is sufficient to perform all the other operations like subtraction, multiplication and division. If we are allowed to use loops and arbitrary integers on the way, it is relatively straightforward ho to implement negation using addition:

1
2
3
4
5
6
7
8
9
int negate(int x){
	int d = x < 0 ? 1 : -1; // determine sign of the increment
	int neg = 0;
	while (x != 0){ // add increment into neg until x is zero
		x += d;
		neg += d;
	}
	return neg;
}

How to make addition? Since nothing available - turn to bit manipulations. Since we work with base 2, when adding two ints we compare them bit by bit. If relative bits are equal (0, 0 or 1, 1) then 0 goes to the sum; if they are different - 1. That is essentially a XOR operation. Yet we need to care about carrying overflow (when adding 1 and 1). Only 1, 1 is found by AND. Since it goes to the more significant bit, we also need to shift « one bit to the left. Once we have sum and carry, we need to add them up - using the same procedure, recursively. Base case to stop - if carry is 0. Here is the code:

1
2
3
4
5
6
7
8
int addWithoutAriphmetic(int a, int b){
	if (b == 0){
		return a;
	}
	int sum = a ^ b;
	int carry = (a & b) << 1;
	return addWithoutAriphmetic(sum, carry);
}

That was mind boggling, now easy stuff: carefully implement remaining operators:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
int substract(int a, int b){
	return a + negate(b);
}

int multiply(int a, int b){
	if (a < b){ //to make if faster
		int tmp = a;
		a = b;
		b = tmp;
	}
	int res = 0;
	boolean bneg = b < 0;
	if (bneg){
		b = negate(b);
	}
	for (int i = 0; i < b; i++){
		res += a;
	}
	if (bneg){
		res = negate(res);
	}
	return res;
}

int divide(int a, int b){
	if (b == 0){
		throw new java.lang.ArithmeticException("divide by zero");
	}	
	boolean aneg = a < 0;
	boolean bneg = b < 0;
	
	if (aneg){
		a = negate(a);
	}
	if (bneg){
		b = negate(b);
	}
	
	if (a < b){
		return 0;
	}
	
	int res = 0;
	int sum = b;
	while (sum <= a){
		sum += b;
		res ++;
	}
	
	if ((aneg && !bneg) || (!aneg && bneg)){
		res = negate(res);
	}
	return res;
}
(Read More...)

To check if the number N is a prime we can either generate with the Eratosthenes Sieve the bool array for all the numbers <= N and them sipmly check if true. However, that seems like overkill to me (especially for big N), so let’s try something different while using all the knowledge about primes we already have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def is_prime(n):
	# Let's check primitive cases
    if n <= 1:
        return False
    elif n <= 3:
        return True
    elif n % 2 == 0 or n % 3 == 0:
        return False

	# Now: any number can be represented as 6k + i, where i = 0..5 <-> i = -1..4
	# (6k + 0),(6k + 2) and (6k + 4) are divisible by 2 -> hence not primes
	# (6k + 3) is divisible by 3 -> hence not prime
	# Thus of all numbers, only those with format (6k - 1) or (6k + 1) left. Let's check them only:
    i = 5 #first 6k - 1
    while i * i <= n: #since primes are only before sqrt(n)
        if n % i == 0 or n % (i + 2) == 0: #i + 2 = 6k + 1
            return False
        i += 6
	return True

Thus in this primarily test we only check one third of all the numbers before N, and only if N is not multiple of 2 or 3.

Just for fun, the same in Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
boolean isPrime(int n){
	if (n < 2)
		return false;
	if (n < 4)
		return true;
	if (n % 2 == 0 || n % 3 == 0)
		return false;		
	int sqrt = (int) Math.sqrt(n);
	for (int i = 5; i < sqrt; i += 5)
		if (i == 0 || i + 2 == 0)
			return false;
	return true;
}
(Read More...)

Primary numbers are cool. You can factorize (decompose) any number into product of primes, amazingly, each number has a single unique decomposition. Primes are like simple building blocks for all the other numbers, which are called composites. Generating and checking if number is a prime is the basis for many crypto systems like RSA. So, it make sense to know what’s up.

For generating a set of primes up to N we will use Eratosthenes Sieve method which was written down by this Greek guy. Idea is, as usual, very simple and elegant:

  • Make a list of numbers 2..N.

  • Starting with first element in the list, cross all its multiples in the list.

  • Repeat until no multiples less than N left.

In other words, we just start with the smallest prime (2) and remove all its multiples less than N; then take next prime (3) and do the same; then next prime would be (5) since (4) is already crossed.

Here is Python snippet:

1
2
3
4
5
6
7
8
9
10
11
12
def eratosthenes_sieve(n):
    numbers = [i for i in range(2, n)]
    pi = 0 # index
    while pi < len(numbers): 
        p = numbers[pi] # current prime
        i = 2 # start with closet multiple
        while p * i <= n: # while multiple less than N -> remove it from the list (if it is still in)
            if numbers.__contains__(p * i):
                numbers.remove(p * i)
            i += 1
        pi += 1
    return numbers

That was easy. Okay, let’s try to optimize. Let us observe what happens when we remove multiples:

  • 2 -> remove: 4, 6, 8, 10, 12, 14, 16…

  • 3 -> remove: 6, 9, 12, 15 …

  • 4 -> remove: 8, 12, 16 …

  • 5 -> remove: 10, 15, 20, 25 …

Interestingly, each time we try to find multiples for next prime, we see, that first multiples were already removed on the previous steps. By going further we can prove, that all the multiples less than current prime squared were already removed. That means we can trim this part of checks:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def eratosthenes_sieve_refine(n):
    numbers = [i for i in range(2, n)]
    pi = 0
    while True:
        p = numbers[pi]
        p_sq = p ** 2
        if p_sq > n:
            break
        while p_sq <= n:
            if numbers.__contains__(p_sq):
                numbers.remove(p_sq)
            p_sq += p
        pi += 1
    return numbers

Next optimization is about which structure we use. Instead of expensive checking contains, we can do array of bools:

1
2
3
4
5
6
7
8
import math
def eratosthenes_sieve_bool(n):
    prime_bool = (n + 1) * [True] # since indexing starts with 0
    for p in range(2, int(math.sqrt(n)) + 1): #int floors the float
        if prime_bool[p]:
            for i in range(p ** 2, n + 1, p): # p^2, p^2 + p, p^2 + 2p ...
                prime_bool[i] = False
    return [i for i, elem in enumerate(prime_bool) if elem][2:]

Finally, we can also observe, that all the even numbers are composites. So we can init our bool array with Falses at the beginning; then we can do 2p step instead if singe p, since 2p is always even number.

1
2
3
4
5
6
7
def eratosthenes_sieve_bool_odd(n):
    prime_bool = [True, True, True] + (n / 2 - 1)  * [True, False]
    for p in range(2, int(math.sqrt(n)) + 1): #int floors the float
        if prime_bool[p]:
            for i in range(p ** 2, n, 2 * p):
                prime_bool[i] = False
    return [i for i, elem in enumerate(prime_bool) if elem][2:]

Now let’s check the real performance with N = 2000:

1
2
3
4
5
6
7
8
9
import time
start = time.time()
eratosthenes_sieve(2000)
end = time.time() - start

eratosthenes_sieve exec time: 0.018317937851
eratosthenes_sieve refine exec time: 0.0219550132751
eratosthenes_sieve bool exec time: 0.00025200843811
eratosthenes_sieve bool odd time: 0.000149965286255

Understandably, bool version with both improvements (init with odds and start with p^2) works the fastest.

PS Funny fact: gcd(x,y) * lcm(x,y) = x * y, where gcd - Greatest Common Divisor, lcm - Least Common Multiple.

(Read More...)

For some reason I never really implemented DFS and BFS before. Time has come. Ideas are simple:

  • DFS: Go down to the neighbours and mark vertices on the way until can’t; then go one step back and proceed with the rest of the neighbours.

  • BFS: Put all the neighbours into the queue; poll (pop and remove) from the queue and put all its neighbours into the queue; repeat.

Let’s do it in Java, since it’s the most common interview language. First let’s define a simple graph on integers as a adjacency list:

1
static HashMap<Integer, ArrayList<Integer>> graph = new HashMap<Integer, ArrayList<Integer>>();

Let’s read the graph from the following txt file:

1
2
3
4
5
6
7
8
0 1
1 0 2
2 1 3 4
3 2 5
4 2 6
5 3 6 7
6 4 5
7 5

Now DFS:

1
2
3
4
5
6
7
8
9
10
	static void dfs(int v){
		visited[v] = true; 
		System.out.print("Visiting " + String.valueOf(v) + ": ");
		printBoolArray();
		for (int u : graph.get(v)){
			if (!visited[u]){
				dfs(u);
			}
		}
	}

And BFS:

1
2
3
4
5
6
7
8
9
10
11
12
13
	static void bfs(int v){
		visited[v] = true; 
		System.out.print("Visiting " + String.valueOf(v) + ": ");
		printBoolArray();
		for (int u : graph.get(v)){
			if (!visited[u] && !queue.contains(u)){
				queue.add(u);
			}			
		}
		if (!queue.isEmpty()){
			bfs(queue.poll());		
		}
	}

So BFS a little bit more straight forward, while for BFS we need to create queue and do extra check. Both algorithms are O(E) time complexity.

Source code of the project on Github

(Read More...)

As usual, this app was born to solve the problem, that I encountered way too often to ignore the opportunity for the optimization.

Use Case:

Whenever I walk through campus my cellphone picks up the university’s wifi connection. Since I’m not actually inside the building, the connection is so weak that it barely works. Importantly doesn’t work good enough for Skyping, which is logical thing to do when you walk through campus without doing anything useful. To fight that problem I normally turned wifi off.. and surely kept forgetting to turn it back on whenever arrived, which led to extra cell traffic consumption and tha lack of in-time sync (e.g. I only sync photos with wifi).

As a solution I made this android app that allows to turn your wifi OFF for X minutes (you can adjust and save X); then it automatically turns it back ON.

Enjoy!

Wifi X Min OFF App

(Read More...)