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:
Anonymous2015-01-08 4:27
I'll concede that it is both useless and an algorithm, but I don't see how it is particularly weird.
Here let me help out your algorithm Let a=A, b=B and c=0. Skip the next line. 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.
Name:
Anonymous2015-01-08 15:19
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 - 1); }
Name:
Anonymous2015-01-08 15:25
isn't that like abs(B-A)
not useless at all
Name:
Anonymous2015-01-08 15:37
>>5 Fuck, right, no subtraction. 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))); }
Name:
Anonymous2015-01-08 16:46
Why are you guys spoilering your algorithms?
Name:
Anonymous2015-01-08 19:28
None of the code in this thread works.
Name:
Anonymous2015-01-09 3:07
>>9 Have you even tried it? I haven't implemented >>1chan'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; }
return a <= b ? 0 : b == 0 ? a : sub (a + (~((int)0)), b + (~((int)0)));
Name:
Anonymous2015-01-09 4:01
>>10 Have you tried them on the specified machine?
>>1 is incorrect for the case a = 0, b = 0. >>7 is incorrect for using operations not present on the specified machine. The commentary in >>10 is incorrect for italicizing subtrahends inappropriately, see this sentence for an example of correct application of italics to a term.
The following algorithm takes an integer X as input and, if X is a perfect square, its output is the square root of X. Otherwise, its output is zero.
Given X: 1: Let a=1, b=3, c=1. 2: Go to line 4. 3: Let a=a+b, b=b+2, c=c+1. 4: If a=X, return c as the answer. If a>X, return 0 as the answer. 5: Go to line 3.