5
\$\begingroup\$

Write a program which prompts a user to input two integers A and B, the program should determine whether A is greater than or lesser than B without the use of greater than [>] or less than [<] operators (and similar operators or methods like .compare) and should output :

Integer A is greater than B.



Rules  : No Brainfuck.

Should work for negative numbers. Signed int. Code's for equality isn't necessary.

Edited Again.

\$\endgroup\$
  • 2
    \$\begingroup\$ What size int? Signed or unsigned? And where's the challenge? Looks pretty trivial to me. \$\endgroup\$ – Peter Taylor Aug 11 '11 at 7:37
  • 4
    \$\begingroup\$ Actually, as written, return a!=b could be argued to meet the spec (it determines whether a is (greater than or less than) b). \$\endgroup\$ – Peter Taylor Aug 11 '11 at 10:14
  • 1
    \$\begingroup\$ As it stands this is too underspecified to make a viable problem in my eyes. −1 from me until this is rectified. \$\endgroup\$ – Joey Aug 11 '11 at 12:08
  • 2
    \$\begingroup\$ I take back the bit about being pretty trivial, given the number of people submitting buggy answers. \$\endgroup\$ – Peter Taylor Aug 11 '11 at 13:01
  • 3
    \$\begingroup\$ Oh. Crap. Sorry. \$\endgroup\$ – Mob Aug 11 '11 at 14:02

25 Answers 25

10
\$\begingroup\$

Javascript

Here's the basic format of all the solutions. This case returns true if a>b and false otherwise:

function greaterThan(a,b){
    c=a;//Copy a
    while(true){
        if(b==a){
            return false;
        }
        if(b==c){
            return true;
        }
        a++;//Approaches b if a<b
        c--;//Approaches b if a>b
    }
}

Warning: Since we didn't need to support the A==B case, the next 3 solutions will lock up for those inputs. Thus, don't fill in equal or empty numbers at the prompts in the test fiddles, unless of course you like pushing red buttons that say "Do NOT push!!!"

149 chars - Fiddle: Conforms EXACTLY to specs ;)

for(A=B='A',C='B',a=c=prompt(A),b=prompt(C);b!=c++||(B=C),b!=a--||(A=C),A==B;);alert("Integer "+B+" is Greater than "+A+".\n\n\nRules : No Brainfuck.")

74 chars - Fiddle: Prompts user for 2 numbers, alerts '-1' if 1st<2nd, '1' if 2nd>1st:

for(A=0,a=c=prompt(),b=prompt();b!=c++||(A=-1),b!=a--||(A=1),!A;);alert(A)

54 chars - Fiddle: Function that takes 2 parameters and returns true if A > B, false if A < B, and, of course, locks up if A==B.

function a(a,b){for(c=a;b!=++a&&b!=--c;);return b!=a;}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ How about with decimals? \$\endgroup\$ – Steve Robbins Aug 12 '11 at 0:47
  • \$\begingroup\$ "Function that takes 2 parameters and returns true if A > B, false if B < A" ... A>B and B<A are the same thing :) \$\endgroup\$ – Andbdrew Aug 12 '11 at 9:49
  • \$\begingroup\$ @imoda: The current solution definitely won't work with decimals. However, it could be modified to work with decimals to a certain precision by adding/subtracting by that precision instead of 1. However, because JavaScript uses floats, the max number you can check will approximately be multiplied by that precision. e.g. 1000000000000001==1000000000000001, 10000000000000001==10000000000000000, 1.000000000000001==1.000000000000001, 1.0000000000000001==1 \$\endgroup\$ – Briguy37 Aug 12 '11 at 13:57
  • \$\begingroup\$ @Andbdrew: Thanks, updated :) \$\endgroup\$ – Briguy37 Aug 12 '11 at 13:58
  • 1
    \$\begingroup\$ Although this is not a code golf question, I would like to challenge you :) function a(a,b){return((a-b)/Math.abs(a-b))==1} - 47 bytes. \$\endgroup\$ – pimvdb Aug 13 '11 at 12:36
6
\$\begingroup\$

Python

from sys import argv as s
a,b=int(s[1]), int(s[2])
if a==b:
 print 'They are the same!'
else:
 print 'Integer A is greater than B.' if (abs(a-b)==a-b) else 'Integer B is greater than A.'

Python - 73 characters

if inputs as arguments is acceptable as 'input', it is only 73 characters:

def c(a,b):
 if a==b:
  return 'They are the same!'
 else:
  return 'Integer A is greater than B.' if (abs(a-b)==a-b) else 'Integer B is greater than A.'

if the weak inequality is all we care about, and we don't have to take input, it's shorter (33 characters):

print a if (abs(a-b)==a-b) else b
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ "Write a program" would seem to imply that more than a function is required. But then it's code-challenge rather than code-golf, so length isn't so important. \$\endgroup\$ – Peter Taylor Aug 11 '11 at 13:02
  • \$\begingroup\$ good point. I switched the order of my responses. \$\endgroup\$ – Andbdrew Aug 11 '11 at 13:13
  • \$\begingroup\$ btw.: It's not a golf. \$\endgroup\$ – user unknown Aug 11 '11 at 17:33
  • \$\begingroup\$ What output do you get for 2000000000, -2000000000? \$\endgroup\$ – Peter Taylor Aug 11 '11 at 21:06
  • \$\begingroup\$ "Integer A is greater than B." \$\endgroup\$ – Andbdrew Aug 11 '11 at 21:39
5
\$\begingroup\$

C

#include<stdio.h>

int main(int argc, char** argv) {
    int a, b;
    long long c;
    double d;
    printf("A: ");
    scanf("%d", &a);
    printf("B: ");
    scanf("%d", &b);
    c = (long long)a - (long long)b;
    if (c == 0) {
        puts("Integer A is equal to B.");
    }
    else {
        d = *(double*)&c;
        if (d == d) {
            puts("Integer A is greater than B.");
        }
        else {
            puts("Integer B is greater than A.");
        }
    }

    return 0;
}

It was golfed but then I realized this wasn't a golf. So now it's not. ;)

To understand how this works, you have to understand how numbers are integers and floats are represented, bitwise, and how the CPU operates on them.

I'm starting out by getting two 32-bit signed integers. They are stored as ints to bound the input. I then cast them to long longs, basically converting them to 64-bit integers, and then subtract. This subtraction is important. If A is larger than B, the result will be positive. If they're equal, the result is 0, and if B is larger than A, the result is negative. The negative case is the key, here, because of how it's represented as an integer in memory. A negative integer is stored as a 2's complement, and since these are 64-bit integers, we'll have at least one DWord of 1s in the MSBs in memory. I then store that into a 64-bit double variable, turning it into a double value with the same bit encoding. If it is negative, this double value is a NaN. By IEEE floating point rules, comparing a NaN with itself will always result in false, which indicates that A < B.

And of course, a simple zero check can add an equivalence check to the algorithm.

EDIT: This now works for very large and very small ints. It requires a 64-bit compiler, where long long is defined as having a size of 8 bytes. Unfortunately, gcc in Cygwin didn't do the trick, so I had to use Visual Studio. But, it works. This, I found, does not work for very large and very small 32-bit integers. I will be investigating a solution.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ When the CPU operates on a NaN, it will flip some of the bits to be only the ones that need to be 0 for it to be considered a NaN. Doesn't this depend on the compiler flags and processor? There are different types of NaN for a reason. \$\endgroup\$ – Peter Taylor Aug 12 '11 at 7:16
  • \$\begingroup\$ @joey, @Peter Taylor: c = (long long)a - (long long)b; well, how is that different than my (removed) suggestion? \$\endgroup\$ – Harry K. Aug 12 '11 at 8:32
  • \$\begingroup\$ @Harry, it's promoting the 32-bit ints to 64 bits before doing the subtraction. That guarantees that it will stay in range. \$\endgroup\$ – Peter Taylor Aug 12 '11 at 8:41
  • \$\begingroup\$ @Peter Taylor: we don't understand each other :lol: What if a and b are defined as long long in the first place (now they are limited to values between INT_MIN - INT_MAX). Even with the revised specs I could for example legitimately claim that restricting the input values to such a small range is a bigger flaw than defining a and b as long long and don't check for overflowing. You see what I'm saying here? Unless you input a and b as strings to be converted later you can't control overflowing against the maximum representable integer in C. \$\endgroup\$ – Harry K. Aug 12 '11 at 9:04
  • 1
    \$\begingroup\$ In theory there are traps you can set up, but I don't know whether the CPUs in actual use make them available, and if so whether compilers do. OTOH I've thought about it some more too and it's irrelevant whether the NaN is normalised or not, because it will still compare to be different to itself anyway. \$\endgroup\$ – Peter Taylor Aug 12 '11 at 17:40
4
\$\begingroup\$

Python

r="less"
try:(input()-input())**.5;r="greater"
except:pass
print "Integer A is",r,"than B"
| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

Since most of the questions about the spec have been answered, here's a solution in C#. If the size of the ints isn't 32-bit then int needs changing for a suitable type.

namespace Sandbox {
    class Program {
        private static int _Compare(int a, int b) {
            if (a == b) return 0;
            int sgnA = (a & int.MinValue) == int.MinValue ? -1 : 1;
            int sgnB = (b & int.MinValue) == int.MinValue ? -1 : 1;
            // If they have different signs then the negative one is smaller.
            if (sgnA != sgnB) return sgnA;
            // If they're both non-negative then the difference won't overflow.
            // If they're both negative, then the different won't overflow. Worst case is (-1) - int.MinValue = int.MaxValue
            return ((a - b) & int.MinValue) == int.MinValue ? -1 : 1;
        }

        public static void Main(string[] args) {
            if (args.Length == 0) {
                // Test mode.
                int[] cases = new int[] {
                    int.MinValue,
                    int.MinValue + 1,
                    int.MinValue + 2,
                    int.MinValue / 2 - 2,
                    int.MinValue / 2 - 1,
                    int.MinValue / 2,
                    int.MinValue / 2 + 1,
                    int.MinValue / 2 + 2,
                    -2, -1, 0, 1, 2,
                    int.MaxValue / 2 - 2,
                    int.MaxValue / 2 - 1,
                    int.MaxValue / 2,
                    int.MaxValue / 2 + 1,
                    int.MaxValue / 2 + 2,
                    int.MaxValue - 2,
                    int.MaxValue - 1,
                    int.MaxValue,
                };
                foreach (int _a in cases) {
                    foreach (int _b in cases) {
                        int _cmp = _Compare(_a, _b);
                        Console.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}", _a, _b, _cmp, _cmp == _a.CompareTo(_b) ? "OK" : "Error"));
                    }
                }
            }
            eise if (args.Length != 2) {
                Console.Error.WriteLine("Expected two arguments.");
            }
            else {
                int a, b;
                if (!int.TryParse(args[0], out a) || !int.TryParse(args[1], out b)) { Console.Error.WriteLine("Both arguments must be integers"); return; }

                int cmp = _Compare(a, b);
                Console.WriteLine(cmp == -1 ? "Integer A is less than B" : cmp == 0 ? "Integer A equals B" : "Integer A is greater than B");
            }
        }
    }
}

All of the test cases pass.

| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

Scala

Based on the revised question:

object G extends App
{
    def g(i:BigInt,j:BigInt)=
    {
        def q(a:BigInt,b:BigInt):String=
        {
            if(a==0)
                "Integer B is greater than A."
            else 
                if(b==0)
                    "Integer A is greater than B."
                else
                    q(a+1,b-1)
        }
        if(i!=j)q(i-j,i-j)else"A and B are equal"
    }
    val(a,b)=(readLine("A: ").toInt,readLine("B: ").toInt)
    println(g(a,b))
}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ The numbers should be read from the user somehow, at least that's how I understand »a number inputted«. \$\endgroup\$ – Joey Aug 11 '11 at 11:47
  • \$\begingroup\$ ` scala G A: 2000000000 B: -2000000000 Integer B is greater than A.` \$\endgroup\$ – user unknown Aug 11 '11 at 15:27
  • \$\begingroup\$ @user unknown I've changed to BigInts to solve that, but when the numbers get that big, it's probably to slow to be useful anyway. Which is why they invented < and > I guess. \$\endgroup\$ – Gareth Aug 11 '11 at 15:32
3
\$\begingroup\$

Javascript: (108 chars without spaces)

function C(a,b) {
    var d=a-b,
        z=!!(d/Math.abs(d)+ 1),
        m=z?a:b,
        n=z?b:a;
    return 'Integer '+m+' is greater than '+n;
}

tests:

console.log( C (1, 3) );    // Integer 3 is greater than 1
console.log( C (3, 2) );    // Integer 3 is greater than 2
console.log( C (-3, -8) );  // Integer -3 is greater than -8
console.log( C (-9, 0) );   // Integer 0 is greater than -9

Code for equality is not required, so I didn't do it.

| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

Scala:

object G extends Application {
  def g (a: Byte, b: Byte) = (a & -128, b & -128) match {
        case (0, 0) => if (((a - b) & -128) != 0) "<" else ">"
        case (x, 0) => "<"
        case (0, x) => ">"
        case _ => if (((b-a) & -128) != 0) ">" else "<"
  }
  val r = g (readByte, readByte)
  println ("A is " + (if (r==">") "greater than" else "less than") + " B")
}

Since ints vary from language to language, I choosed Bytes here, because it allowed me to do exhaustive testing.

Of course it can easily be adapted to short/int/long, with Int.MIN_VALUE etc. instead of -128.

The 4 cases test for

  • both values are positive
  • only first
  • only second
  • none of them

It took me 60 minutes to golf it down to 297 chars, until I noticed, that it isn't a golf! And another 10 minutes for hitting 80x undo (real programmers don't do backups).

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Ada, 76 Characters

function C(A,B:Integer)return Integer is
begin return (A-B)/abs(A-B);end C;

returns -1 for A smaller than B, and 1 for A bigger than B.

for A=B an exception will be raised, but the behaviour in this case isn't specified in the task description.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

D (51 chars)

int d(int a,int b){return a-b?(a-b)&-1<<31?-1:1:0;}

using signed representation

returns -1,0,1 for less than, equals to and greater than resp.

with reading from user: 91 chars

import std.stdio;void main(){int a,b;readf("%d %d",&a,&b);writeln(a-b?(a-b)&-1<<31?-1:1:0);}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ This isn't a golf, but you can shave a char by using (a-=b)?a ... (May not work in D, I'm not too familiar with it. Unfortunately it seems D has a boolean type, but otherwise you could shave chars by flipping your logic: d(a,b){return(a-=b)&1<<31?-1:!!a;} \$\endgroup\$ – walpen Jun 4 '12 at 23:03
1
\$\begingroup\$

PHP

PHP's too verbose for a task this simple, but I'm in PHP mode so I'll go ahead:

function d($a,$b){return $a-$b;}
// Returns a negative number if $a < $b, positive if $a > $b, 0 if $a == $b

If you need it to always return the same values, then

function d($a,$b){return ($d=$a-$b)?$d/abs($d):0;}
// Returns -1 if $a < $b, 1 if $a > $b, 0 if $a == $b

If you want it to output text, you could do something like:

function d($a,$b){$d=$a-$b;echo !$d?'equal':(abs($d)==$d)?'greater than':'less than';}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 0/0 doesn't give an error of some kind? Also, have you considered test cases near the extremes? I bet you've got a few overflow bugs. \$\endgroup\$ – Peter Taylor Aug 11 '11 at 10:37
  • \$\begingroup\$ True, but the problem isn't very well-defined as it is. I'll fix the 0/0. I haven't tested extreme cases, but maybe PHP's BC Math extension can fix those... \$\endgroup\$ – migimaru Aug 11 '11 at 11:01
  • \$\begingroup\$ The numbers should be read from the user somehow, at least that's how I understand »a number inputted«. \$\endgroup\$ – Joey Aug 11 '11 at 11:47
  • \$\begingroup\$ Well, I guess PHP is out of the running now since the question requires prompting the user. \$\endgroup\$ – migimaru Aug 11 '11 at 13:35
1
\$\begingroup\$

Objective-C - 161 chars + full string

This solution prompts the user, gets the value, and then returns the full string.

Usage - self-explanitory, it requests a with 'a?' and then once inputted, requests b with 'b?'.

int a,b,x;char c='A';NSLog(@"a?");scanf("%i",&a);NSLog(@"b?");scanf("%i",&b);
x=(a-b/abs(a-b)==1);NSLog(@"Integer %c is greater than integer %c.",c+!x,c+x);

And readable version (with whitespace)

int a,b,x;
char c = 'A';
NSLog(@"a?");
scanf("%i", &a);
NSLog(@"b?");
scanf("%i", &b);
x = (a-b/abs(a-b) == 1);
NSLog(@"Integer %c is greater than integer %c.", c+!x, c+x);

Output:

Computer: a?
Me: 2 
Computer: b? 
Me: 3 
Computer: Integer B is greater than integer A.
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

C

void AgB(int a, int b) {
(( 2 * a + 1) / (2 * b + 1) == 0) ? printf("Integer B is greater than A\n") : printf("Integer A is greater than B\n");}
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Python alt-way

#!/usr/bin/python

import sys
a, b = map(int, sys.argv[1:3])
s = '==' if (a == b) else '<' if (str(a-b)[0] == '-') else '>'
print 'a(%d) %s b(%d)' % (a, s, b)
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

If equility is not matter, just doing sorted([A,B]) != [A,B] should do, so

a=[input(),input()];print"A is "+["less","great"][sorted(a)!=a]+"er than B"

Tests

>>> a=[input(),input()];print"A is "+["less","great"][sorted(a)!=a]+"er than B"
1
2
A is lesser than B
>>> a=[input(),input()];print"A is "+["less","great"][sorted(a)!=a]+"er than B"
2
1
A is greater than B
>>> a=[input(),input()];print"A is "+["less","great"][sorted(a)!=a]+"er than B"
-1
-2
A is greater than B
>>> a=[input(),input()];print"A is "+["less","great"][sorted(a)!=a]+"er than B"
-2
-1
A is lesser than B
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Python, 152 characters

Conforms to the letter with the specification.

No cheating with conditionals of any kind, including equality. The abs call probably has a conditional hidden, if I weren't golfing I would do x/=int(math.sqrt(x*x)) as the third line.

i=input
x=i("A")-i("B")
x/=abs(x)
print "Integer",chr((131-x)/2),"is greater than",chr((131+x)/2)+".\n\n\n\nRules  : No Brainfuck."
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

BF, handles negative zero

I figured it would be fun to invent a language for the job, using characters < and > for something completely unrelated to inequality comparison.

# parse first number (space delimited)
+>,---------------------------------------------
[<->[->+<]]<[->+>,---------------------------------------------<<]>
>+++++++++++++[
  <<[->>>+<<<]>>----------------
  [-<<+>>]>[-<<<++++++++++>>>]<
  ,--------------------------------]
# parse second number (newline delimited)
+>,---------------------------------------------
[<->[->+<]]<[->+>,---------------------------------------------<<]>
>+++++++++++++++++++++++++++++++++++[
  <<[->>>+<<<]>>--------------------------------------
  [-<<+>>]>[-<<<++++++++++>>>]<
  ,----------]
# handle minus signs
<[<<[-<[->+<]>>[-<<+>>]<[->+<]>>-<<]>>[-<[-]<<+>>>]]
<<[-<[-]>>+<]
# compare
<+>>+[-<<-[>]>]
# report
>[[-]++++++++++++++++++++++++++++++
     ++++++++++++++++++++++++++++++.<]
<<<[[-]+++++++++++++++++++++++++++++++
       +++++++++++++++++++++++++++++++.>]

For a brief summary of operators: < and > move the cursor backward/forward; +/- increment/decrement the value of the number pointed to by the cursor (hereafter referred to as "the accumulator"); [] iterate while the accumulator is non-null; , reads a byte from input to the accumulator; . writes the accumulator to the output. Anything else is ignored, which provides a cool way to implement comments, that can even be made to look like comments in other scripting languages.

Handles negative numbers by checking for the following cases:

  • if both numbers are signed negative, swap them
  • if only one number is negative, zero it out and increment the other one
  • else just leave them alone

This lets us compare zero with negative zero (-0 < 0). Equality is not handled.

Funny how I/O takes more than twice the space the math does.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Python, 86

a,b=input('A,B')
print 'Integer A is %s than B.'%('less'if abs(a-b)-a+b else'greater')
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Haskell, 150 characters

main=putStr.g.f.map read.words=<<getLine
f[a,b]|b`elem`dropWhile(/=a)[(minBound::Int)..]="BA"|0<1="AB"
g[x,y]="Integer "++x:" is greater than "++y:"."

I could use Integer and do subtraction, but I felt like dealing with overflow problems that arise from using Int.

Note there is a < in the code, but it is used to compare a constant expression (one character less than writing True).

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

FORTRAN 77

I guess good old Fortran arithmetic if does not violate the requirements of the question. Here it is

      PROGRAM TEST
      READ *, A
      READ *, B
      IF (B-A) 99,100,101
99    PRINT *, 'Integer A is greater than B'
      GOTO 102
100   PRINT *, 'they are equal'
      GOTO 102
101   PRINT *, 'Integer B is greater than A'
102   STOP
      END
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

C# approach with 44 chars. I just subtract a from b and check if there is a minues in the result string:

bool c(int a, int b){return ("" + (b - a))[0] == 0x2d;}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 0x2d could be replaced with "-"! -1 char \$\endgroup\$ – cansik Jun 8 '12 at 13:04
0
\$\begingroup\$

Haskell - 18 characters

main=print.compare

Returns GT if a > b, LT if a < b.

Or since this question's output is completely unspecified, I can do

main=print.(-) 

which returns a negative number if a < b, or a positive number if a > b.

EDIT: I didn't see what the exact output has to be (see below)

main = print.f
f x y|q==GT=g b|q==LT=g c where q=compare x y
a="Integer A is "
b="greater than"
c="less than"
e=" B."
g x=a++x++e

BTW, this golf sucks.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ What does it return if a==b? And how does it get its input? I only ask because I know nothing about Haskell. \$\endgroup\$ – Gareth Aug 11 '11 at 13:23
  • \$\begingroup\$ compare would return EQ if a==b. \$\endgroup\$ – matt Aug 11 '11 at 13:24
  • \$\begingroup\$ This will read two Integers and print Integer A is greater than B.? \$\endgroup\$ – user unknown Aug 11 '11 at 14:42
  • \$\begingroup\$ Dang. This doesn't count. Revised the question \$\endgroup\$ – Mob Aug 11 '11 at 14:50
  • 2
    \$\begingroup\$ He revised the question after I submitted this. \$\endgroup\$ – matt Aug 12 '11 at 12:21
0
\$\begingroup\$

C (K&R) - 49 chars

This is indeed trivial...

a,b;main(){scanf("%d%d",&a,&b);printf("%d",a-b);}

negative result if a > b, positive if a < b, 0 if equal

EDIT: This answer corresponds to the very first specs of the question, when golfing was required and the output was not restricted to specific phrases.

| improve this answer | |
\$\endgroup\$
  • 2
    \$\begingroup\$ Undefined behavior if a-b overflows. \$\endgroup\$ – Joey Aug 11 '11 at 11:28
  • 1
    \$\begingroup\$ @joey: tsk, tsk... too picky! The problem doesn't talk about overflows/underflows and the author didn't answer to the relative question. If you have a better suggestion which checks input against the range INT_MIN to INT_MAX without using > or < I'd be happy to see it. Until then I consider your down-vote to be rather harsh! Keep also in mind that there will always be at least one number that overflows any of the built-in data types on input, no matter what data type you choose to represent a and b. \$\endgroup\$ – Harry K. Aug 11 '11 at 12:00
  • \$\begingroup\$ UB is a rather special case for C and derivates, but as long as your using signed ints and do that subtraction you have UB. Which means that there are inputs where your method isn't guaranteed to give the correct result. Just because over-/underflows are defined in other languages doesn't make it ok to rely on that in C, in my eyes. But agreed, the question is underspecified in any case. The easiest fix, conforming to the question would probably be to make a and b unsigned (where it is defined). \$\endgroup\$ – Joey Aug 11 '11 at 12:05
  • \$\begingroup\$ @joey: but then you rule out negative numbers both on the input and on the result, which someone could legitimately consider it to be a bigger flow than not checking for overflows. Plus, you don't solve the over/underflow problem either. \$\endgroup\$ – Harry K. Aug 11 '11 at 12:20
  • 1
    \$\begingroup\$ Surely handling overflow is the essence of the problem. Without that it's a "challenge" consisting of "Can you tell whether an int is negative without using < or >?" \$\endgroup\$ – Peter Taylor Aug 11 '11 at 19:43
0
\$\begingroup\$

Perl

for(0..9){
 $s.=("2"x$_)."1".("0"x(9-$_))
}
for(0..9){
  $a=$_;
  for(0..9){
   $c[$a][$_]=chop$s
  }
}
$_=<>;
$b=<>;
$l=length;
$_="0"x length$b.$_;
$b="0"x$t.$b;
for(1..$l){
 $e.=chop;$f.=chop$b
}
$g="Integer A is";
$h=" than Integer B";
for(1..$l){
 $t=$c[$_][$b];
 if($t==2){die"$g less$h"}
 if($t==0){die"$g greater$h"}
}

This creates a look-up array for all of the comparisons of each digit. It then takes two unsigned integers as input. It makes them the same length. It then compares them one digit at a time using the look-up array. I am sure it could be made a lot shorter.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

JavaScript (65)

Enter in Mozilla Firefox's Web Console:

'Integer A is '+(eval(prompt())>>>31?'less':'greater')+' than B.'

The user should separate the two signed integers (which should each fit in 31 bits) with " - ". The program takes the difference and checks the sign bit.

| improve this answer | |
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.