Exchange the bits at even and odd positions

Write code to exchange the bits at even and odd positions in a number.

Answer:


/**
* Program to exchange the bits at even and odd positions
* */
#include "stdio.h"
#include "stdlib.h"

void PrintBinary(size_t num)
{
for( int i = 31; i >=0; --i )
if ( num & ( 1 << i) )
printf("1");
else
printf("0");
printf("\n");
}

size_t SwapBits(size_t num)
{
/* Program to reverse the bits of a number */

return ( (num << 1) & 0xAAAAAAAA ) |
( (num >> 1 & 0x55555555) );
}

int main(int argc, char* argv[])
{
for ( int i = 1; i <= argc-1; ++i )
{
size_t num = atoi(argv[i]);
PrintBinary(num);
PrintBinary(SwapBits(num));
}
return 0;

}

N-Queens problem

Write the algorithm for N-Queens problem.

Answer:


Board[n] = {}


bool isColliding(int row, int col)
{
for ( i = 1; i < row; ++i)
{
/* diagonal collision */
if ( abs(row -i) == abs(col - Board[i] ) )
return false;
/* columnar collision */
if ( Board[i] == col )
return false;
}
return true;
}

void placeQueen(int row, int col)
{
Board[row] = col;
}

void Iterative_NQueens()
{
for (row=1; row <= n; ++row)
{
for(col=1; col <= n; ++col )
{
if ( isColliding(row,col) )
continue;
else
{
placeQueen(row,col);
if ( row == n )
{
/* print the solution */
}
break; // continue with next row
}
}
}
}

void Recursive_NQueens(int _row)
{
for (row = _row; row <= n; ++row)
{
for(col=1; col <= n; ++col )
{
if ( isColliding(row,col) )
continue;
else
{
placeQueen(row,col);
if ( row == n )
{
/* print the solution */
return;
}
else
/* next row */
Recursive_NQueens(_row + 1);
}
}
}
}


Generation of Prime Numbers

Write an algorithm to generate the prime numbers.

Answer:

Several solutions exist, the basic solution is to use the sieve technique.
Basic Solution:

prime_nos = [1,2]
bas
for ( i = 3 to n )
{
if (i is divisible by any number < sqrt(i))
{
then i is not prime
i += 2; // increment by two, optimization, since even numbers
// cannot be prime.
}
else
{
add i to the prime_nos list.
}

}


Well known algorithms:
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
http://en.wikipedia.org/wiki/Sieve_of_Atkin

Also as per wikipedia:

One method for determining whether a number is prime is to divide by all primes less than or equal to the square root of that number. If any of the divisions come out as an integer, then the original number is not a prime. Otherwise, it is a prime. One need not actually calculate the square root; once one sees that the quotient is less than the divisor, one can stop.