A hard problem! Get maximum one of two natural numbers.

Started by
221 comments, last by The C modest god 18 years, 2 months ago
Quote:Original post by ZeRaW
nobody replied if mine was correct:


unsigned int MaxValue(unsigned int a1, unsigned int a2)
{
return (bool)(a2/(a1+1))*a2 + (bool)(a1/(a2+1))*a1 + (1-(bool)(a1-a2))*a1;
}


I tested it with a few numbers and it seemed to work.
is type casting to bool acceptable?


I got a divide by zero excpetion when using a = 0xfffffffa, b = 0xffffffff.

If casting is allowed, there is a quite simple solution:
unsigned int myMax(unsigned int a, unsigned int b){	unsigned int za = 1 - (unsigned int)bool(a);	unsigned int ma = (unsigned int)bool(b / (a + za));	return (b - a) * ma + a;}

Advertisement
Quote:Original post by sindre
Quote:Original post by eq
Write the shortest (least number of instructions) solution for the same problem in x86 assembler, using nothing more than the add, sub, div, mul and mov instructions (immediates and registers are the only allowed operands).

I wanna use adc [bawling]
*** Source Snippet Removed ***


I want to use cmp and cmov :)
  cmp   eax, edx  cmova eax, edx


I found a way to shorten my asm method down:

	mov ebx, eax	mov edi, edx	mov ecx, eax	mov esi, 0xffffffff	mov edx, 0	add eax, esi	div esi	add ebx, eax	mov eax, edi	mov edx, 0	div ebx	add eax, esi	mov edx, 0	div esi	sub ecx, edi	mul ecx	add eax, edi
Quote:Original post by Anonymous Poster
Quote:Original post by The C modest god
I didnt read your answer, but I have found my own answer. Here it is.

int Max (unsgined int a, unsgined int b)
{
signed int dif, pos;

dif = (signed int)a-(signed int)b;
pos = (dif+dif*dif)/(dif*dif) // Will be one if dif positive, zero if negative
return (unsigned int)((signed int)b+dif*pos);
}


What do you say?


That's no even valid C++ code!
What's "unsgined"?
Furthermore there's a missing ';' and the return value should be unsigned as well.
I modified it so that the code actually works:
*** Source Snippet Removed ***

This causes a division by zero when a = b.
Also it doesn't work for several cases such as a = 0x1c and b = 0x1b, it then returns 0x1d.

You are right, there is a problem when dif equal 1 or 0.
Here is a correction:
unsigned int Max (unsigned  int a, unsigned  int b){   signed int dif, pos;   dif = (signed int)a-(signed int)b;   pos = (dif+dif*dif)/((dif*dif)+1); // Will be one if dif positive, zero if negative   return (unsigned int)((signed int)b+dif*pos);}


It's all about the wheel.Never blindly trust technoligy.I love my internal organs.Real men don't shower.Quote:Original post by Toolmaker Quote:Original post by The C modest godHow is my improoved signature?It sucks, just like you.

This topic is closed to new replies.

Advertisement