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

Weird useless algorithm

Name: Anonymous 2015-01-08 3:56

How to subtract the smallest of two integers from the greater one, in a system that supports only addition, equality comparisons and conditional jumps:

The numbers are A and B.
If A=B, return 0 as the answer.
Define three numeric variables a, b and c of the same type as A and B.
Let a=A, b=B and c=0.
Now let c=c+1, a=a+1 and b=b+1.
If either a=B or b=A, go to the next line. Otherwise, go to the previous line.
Return c as the answer.

The algorithm is not mine, by the way. It's anonymous.

Name: Anonymous 2015-01-09 3:07

>>9
Have you even tried it? I haven't implemented >>1 chan's code, but >>7 works fine. It also segfaults for me for subtrahends larger than 524119, unless compiled with -O2. I never would have thought GCC to be so lowly as to not optimize recursive tails without being told too. I swear, half the time it thinks it's smarter than I am and wrecks shit, the other half is shit like this.

extern long atol(const char *);
extern int printf(const char *, ...);

unsigned int sub(unsigned int a, unsigned int b)
{
if(a <= b) return 0;
if(b == 0) return a;
return sub(a + (~((int)0)), b + (~((int)0)));
}

int main (int argc, char* argv[]){
printf("%u", sub(atoi(argv[1]), atoi(argv[2])));
return 0;
}

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