Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

NEED URGENT HELP

Name: edo-chan 2011-12-28 11:11

sup /prog/

Ive asked this everywer already but peopl seem too lame to make even a simple program like so i hope the mighty anon programers of 4chan are more skilled

what im trying to do is to Write a method taking two parameters x and n that computes the nth power of x without using ^ or declaring a new variable inside the method or using Math lib.
and it has to be coded in JAVA (i know it sux but dont ask why i use dat shit)
hep plox!

Name: Anonymous 2011-12-30 0:30

>>182

[ Fri Dec 30 12:28:54 ]
[ @ ~/host/prog/fib ] $ cat fib.c
#include <stdlib.h>
#include <stdio.h>

/* Recursive */
unsigned long long rfib(const int n)
{
    return (n < 2) ? n : rfib(n - 1) + rfib(n - 2);
}

/* Tail Call */

unsigned long long tcfib(const unsigned long long a,const unsigned long long b,const int n)
{
    return n < 1 ? a : n == 1 ? b : tcfib(b,a+b,n - 1);
}


unsigned long long tfib(const int n)
{
    return tcfib(0,1,n);
}


int main(int argc,char **argv)
{
    int n = atoi(argv[2]);
    switch(atoi(argv[1])){
    case 0: printf("%d\n",rfib(n)); break;
     case 1: printf("%d\n",tfib(n)); break;
    }
}
[ @ ~/host/prog/fib ] $ time ./fib 0 30
832040

real    0m0.100s
user    0m0.080s
sys    0m0.008s
[ Fri Dec 30 12:26:49 ]
[ @ ~/host/prog/fib ] $ time ./fib 0 40
102334155

real    0m4.745s
user    0m4.732s
sys    0m0.008s
[ Fri Dec 30 12:29:41 ]
[ @ ~/host/prog/fib ] $ time ./fib 1 40
102334155

real    0m0.007s
user    0m0.000s
sys    0m0.004s
[ Fri Dec 30 12:29:47 ]
[ @ ~/host/prog/fib ] $ time ./fib 1 10000
1242044891

real    0m0.007s
user    0m0.000s
sys    0m0.000s



Why would i choose to do ugly for loops when i can make a nice tail call that gets optimized into one under the hood.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List