Compare two numbers

Write a function to compare two numbers and return greater of them without using any comparasion operator and if-else loop.

Comments

  1. int greater( int a,int b )
    {
    int r = ( (b/a)*a+(a/b)*b )/( (b/a)+(a/b) );
    r = ( a+b )-r;
    return r;
    }


    there is a limitation with the above code that it works for positive integers only :(

    ReplyDelete
  2. @jainendra your code works fine for positive numbers but it is taking in account only magnitude so it is not working for negative numbers...

    int greater( int a,int b )
    {
    int r = ((a+b)+abs(a-b))/2;
    return r;
    }

    ReplyDelete
  3. well you are using the in-built function, which may be using the if-else loop...so i guess the purpose is not served completely...but it might be the case that we have no other way :)

    ReplyDelete
  4. @jainendra may be you can try it some other way but you are right abs() may be using some conditional operator internally...

    ReplyDelete
  5. We create an array with of the size of first number. In a try/catch block we access the element with the index of the second number. If the second nr. is smaller then no exception is raised; meaning the index was inside of the bounds. On the countrary if an exception is raised then the second nr was greater, thus an exception is raised.

    Works only for positive values of m, n:



    public static void compare(int m, int n) {
    int[] A = new int[m];

    try {
    A[n-1] = 0;
    // n is smaller then m
    // nothing is returned
    }
    catch (ArgumentOutOfBounds)
    {
    // exception raised
    // n is greater then m
    }

    }

    ReplyDelete
  6. @greatI indeed its good effort but still for checking ArgumentOutOfBounds java must be using comparison operator.And if you will think in terms of space for comparing two numbers you are creating space of the order (either of two numbers)

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. int min a= (j + ((i-j)&(i<j)))
    int max a= (j - ((i-j)&(i<j)))

    compare operator is serving the different purpose as askd in qs..but i will not giv any point to myself for this :) !

    ReplyDelete
  10. @softy32 but still you are not allowed to use this operator..:)

    ReplyDelete
  11. @all i have come up with a solution suggested by my friend..
    int large(int x,int y)
    {
    return x-((x-y)&((x-y)>>sizeof(int)-1));
    }
    i.e for any two value x and y if x-y is +ve msb will be 0 and 1 in other case.

    ReplyDelete

Post a Comment

Popular posts from this blog