# Program that determines whether an int is greater or lesser [closed]

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.

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

## 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;}

• How about with decimals? Aug 12, 2011 at 0:47
• "Function that takes 2 parameters and returns true if A > B, false if B < A" ... A>B and B<A are the same thing :) Aug 12, 2011 at 9:49
• @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 Aug 12, 2011 at 13:57
• 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. Aug 13, 2011 at 12:36
• @pimvdb: Challenge accepted! Not sure if Math.abs is allowed, but if so how about: function a(a,b){return a-b-Math.abs(a-b)} - 41 bytes, or if false and true are required: function a(a,b){return 0==a-b-Math.abs(a-b)} - 44 bytes Aug 31, 2011 at 18:23

# 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

• "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. Aug 11, 2011 at 13:02
• good point. I switched the order of my responses. Aug 11, 2011 at 13:13
• btw.: It's not a golf. Aug 11, 2011 at 17:33
• What output do you get for 2000000000, -2000000000? Aug 11, 2011 at 21:06
• "Integer A is greater than B." Aug 11, 2011 at 21:39

## 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.

• 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. Aug 12, 2011 at 7:16
• @joey, @Peter Taylor: c = (long long)a - (long long)b; well, how is that different than my (removed) suggestion? Aug 12, 2011 at 8:32
• @Harry, it's promoting the 32-bit ints to 64 bits before doing the subtraction. That guarantees that it will stay in range. Aug 12, 2011 at 8:41
• @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. Aug 12, 2011 at 9:04
• 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. Aug 12, 2011 at 17:40

## Python

r="less"
try:(input()-input())**.5;r="greater"
except:pass
print "Integer A is",r,"than B"


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.

## 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"
}
println(g(a,b))
}

• The numbers should be read from the user somehow, at least that's how I understand »a number inputted«.
– Joey
Aug 11, 2011 at 11:47
•  scala G A: 2000000000 B: -2000000000 Integer B is greater than A. Aug 11, 2011 at 15:27
• @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. Aug 11, 2011 at 15:32

## 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.

## 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 "<"
}
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).

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.

## 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);}

• 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;} Jun 4, 2012 at 23:03

## 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';}  • 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. Aug 11, 2011 at 10:37 • 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... Aug 11, 2011 at 11:01 • The numbers should be read from the user somehow, at least that's how I understand »a number inputted«. – Joey Aug 11, 2011 at 11:47 • Well, I guess PHP is out of the running now since the question requires prompting the user. Aug 11, 2011 at 13:35 ## 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.  ## 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");}  ## 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)  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  ## 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."  ## 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. # Python, 86 a,b=input('A,B') print 'Integer A is %s than B.'%('less'if abs(a-b)-a+b else'greater')  ## Haskell, 150 characters main=putStr.g.f.map read.words=<<getLine f[a,b]|belemdropWhile(/=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). ## 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  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;}  • 0x2d could be replaced with "-"! -1 char Jun 8, 2012 at 13:04 ## 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. • What does it return if a==b? And how does it get its input? I only ask because I know nothing about Haskell. Aug 11, 2011 at 13:23 • compare would return EQ if a==b. – matt Aug 11, 2011 at 13:24 • This will read two Integers and print Integer A is greater than B.? Aug 11, 2011 at 14:42 • Dang. This doesn't count. Revised the question – Mob Aug 11, 2011 at 14:50 • He revised the question after I submitted this. – matt Aug 12, 2011 at 12:21 # 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. • Undefined behavior if a-b overflows. – Joey Aug 11, 2011 at 11:28 • @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. Aug 11, 2011 at 12:00 • 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). – Joey Aug 11, 2011 at 12:05 • @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. Aug 11, 2011 at 12:20 • 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 >?" Aug 11, 2011 at 19:43 ## 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.

## 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.