double power(double val, unsigned int pow)
{
if (pow == 0) /* pow(x, 0) returns 1 */
return(1.0);
else
return(power(val, pow - 1) * val);
}
|
int fib(int num)
{
switch(num) {
case 0: return(0); break;
case 1: return(1); break;
default: /* Including recursive calls */
return(fib(num - 1) + fib(num - 2));
break;
}
}
|
| Input Value | Number of invocations |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 3 |
| 3 | 5 |
| 4 | 9 |
| 5 | 15 |
| 6 | 25 |
| 7 | 41 |
| 8 | 67 |
| 9 | 109 |
| 10 | 177 |
#include <stdio.h>
int main()
{
unsigned int num;
unsigned int i, fn, fn_1 = 1, fn_2 = 0;
printf("Enter a non-negative integer: ");
if (scanf("%u", &num) != 1) {
printf("ERROR: failed to read input number!\n");
return -1;
}
if (num == 0)
fn = 0;
else if (num == 1)
fn = 1;
else {
for (i = 2; i <= num; ++i) {
fn = fn_2 + fn_1;
fn_2 = fn_1;
fn_1 = fn;
}
}
printf("Fibonacci of %d is %d\n", num, fn);
return 0;
}
|
void int_comma(int num)
{
if (num < 1000)
printf("%3d", num);
else {
int_comma(num / 1000);
printf(",%03d", num % 1000);
}
}
|
int_comma(893427165) int_comma(893427) int_comma(893) |
#include <stdio.h>
/*! forward declarations */
void move_right(int id);
void move_left(int id);
void move_right(int id)
{
if (0 == id) return;
move_left(id - 1); /* move id - 1 discs one peg to left */
printf("Shift disc %d one peg to right.\n", id);
move_left(id - 1); /* move id - 1 discs one peg to left */
}
void move_left(int id)
{
if (0 == id) return;
move_right(id - 1); /* move id - 1 discs one peg to right */
printf("Shift disc %d one peg to left.\n", id);
move_right(id - 1); /* move id - 1 discs one peg to right */
}
int main(void)
{
move_left(4); /* solve 4 disc problem */
return 0;
}
|
f(e,0) = 0
f(0,b) = 0
f(e,b) = f(e-1,b) + f(e-1,b-1) + 1
#include <stdio.h>
int comp_floors(int exprs, int balls)
{
if (balls == 0)
return 0;
if (exprs == 0)
return 0;
return comp_floors(exprs - 1, balls) + comp_floors(exprs - 1, balls - 1) + 1;
}
int main()
{
int floors, exprs, balls;
printf("Enter number of floors followed by number of balls: ");
if (scanf("%d %d", &floors, &balls) != 2) {
printf("ERROR: cannot read input!\n");
return -1;
}
for (exprs = 0; 1; exprs++) {
if (comp_floors(exprs, balls) >= floors)
break;
}
printf("Required %d exprs\n", exprs);
return 0;
}
|