So one of my friends and I were talking about algorithm analysis and tried to think up a quick and dirty n^n algorithm (that is, one which grows on a more than factorial order) and this is what we came up with. Be forewarned: Calling this function with an argument of more than 30 is likely to eat all your memory (on the school computer we tried it on we got a BSOD. Wheeeeee!)
void int sum(int n)
{
//base case
if(n == 0)
return 1;
int sum = 0;
for(int i = 0; i < n; i++)
sum += sum(i);
return sum;
}
This is like the fibonacci series on crack (in terms of the call hierarchy), though it ends up falling into a pattern of simply doubling. You get a slightly more interesting pattern by switching the initialization of sum from 0 to n, but the main point here is to maximize the number of operations in as little code as possible without generating an infinite loop.
Showing posts with label C++. Show all posts
Showing posts with label C++. Show all posts
Monday, November 15, 2010
Tuesday, November 10, 2009
Function to Print A Value's Bit Representation in Hex (by Casting as an Unsigned Int) in C
void printHex(int someInt)
{
unsigned int temp;
for(temp = (someInt); temp != 0; temp /= 16)
if(temp % 16 <>= 0)
printf("%d", temp % 16);
else
{
switch(temp % 16)
{
case 10:
putchar('A');
break;
case 11:
putchar('B');
break;
case 12:
putchar('C');
break;
case 13:
putchar('D');
break;
case 14:
putchar('E');
break;
case 15:
putchar('F');
break;
}
}
}
{
unsigned int temp;
for(temp = (someInt); temp != 0; temp /= 16)
if(temp % 16 <>= 0)
printf("%d", temp % 16);
else
{
switch(temp % 16)
{
case 10:
putchar('A');
break;
case 11:
putchar('B');
break;
case 12:
putchar('C');
break;
case 13:
putchar('D');
break;
case 14:
putchar('E');
break;
case 15:
putchar('F');
break;
}
}
}
Labels:
C,
Computer Science
Function for Printing An Item in Binary (Will Print in Little Endian) in C
void printBits(int someInt)
{
int counter, mask;
//Loop through the bits 1 by 1, putting out a 1 for every 1 encountered and a 0 for every 1 encountered
for(counter=1, mask=1; counter <= sizeof(int) * CHAR_BIT; counter++, mask*=2)
{
putchar(((someInt & mask)==0) ? '0' : '1');
//Put spaces between every 8 bits
if(counter != 0 && counter % (CHAR_BIT) == 0 && counter <= (sizeof(int) * CHAR_BIT))
putchar(' ');
}
printf("\n\n");
}
{
int counter, mask;
//Loop through the bits 1 by 1, putting out a 1 for every 1 encountered and a 0 for every 1 encountered
for(counter=1, mask=1; counter <= sizeof(int) * CHAR_BIT; counter++, mask*=2)
{
putchar(((someInt & mask)==0) ? '0' : '1');
//Put spaces between every 8 bits
if(counter != 0 && counter % (CHAR_BIT) == 0 && counter <= (sizeof(int) * CHAR_BIT))
putchar(' ');
}
printf("\n\n");
}
Labels:
C,
Computer Science
Subscribe to:
Comments (Atom)