determine if an integer value is odd or is even

Started by RemiD, October 21, 2019, 22:03:41

Previous topic - Next topic

Steve Elliott

Win11 64Gb 12th Gen Intel i9 12900K 3.2Ghz Nvidia RTX 3070Ti 8Gb
Win11 16Gb 12th Gen Intel i5 12450H 2Ghz Nvidia RTX 2050 8Gb
Win11  Pro 8Gb Celeron Intel UHD Graphics 600
Win10/Linux Mint 16Gb 4th Gen Intel i5 4570 3.2GHz, Nvidia GeForce GTX 1050 2Gb
macOS 32Gb Apple M2Max
pi5 8Gb
Spectrum Next 2Mb

TomToad

#16
Quote from: Derron on October 23, 2019, 21:28:38
Ohh no ... seems to contain a mistake.

Quote from: Qube on October 23, 2019, 22:56:30
That's my boy! true brute force at it's best ;D ( even with a bug )

I don't see the bug.  Tried replacing the For loops with
For i = -648 to +647 step 2
For i = -647 to +647 step 2
So that I wouldn't have to wait a month for a result, and the values return correct results.

Edit: Here's another way to determine if a number is odd or even
Function isEven(num%)
If Instr("02468",Right(Str(num),1)) > 0 Then Return True
Return False
End Function

Function isOdd(num%)
If Instr("13579",Right(Str(num),1)) > 0 Then Return True
Return False
End Function


Rube Goldberg use to find complex ways of solving simple problems.  I guess this is the programmer's version of it? :D

------------------------------------------------
8 rabbits equals 1 rabbyte.

Derron

Yepp, no bug - just compared the numbers ("- ...8 to ..." and "- ...7 to ..." and did not grasp the "roll over" at "2^31 -1" +1).

See - your algorithm was already over my head, so it must be the perfect one :)

bye
Ron

iWasAdam

or...

method IsEven:bool( input:int )
  local check:float = input / 2
  return int(check) = check
end method


@Qube - Brilliant!  :))

Derron

#19
@IwasAdam
"int/2" = int (at least in BlitzMax)

so better write "int/2.0" to return the float value.

Yet your

method IsEven:bool( input:int )
  local check:float = input / 2.0
  return int(check) = check
end method

might even be faster than the modulo :)


alternative to yours:

method IsEven:bool( input:int )
  return int(input / 2.0)*2 = input
end method



Back to serious mode:
https://stackoverflow.com/questions/2229107/what-is-the-fastest-way-to-find-if-a-number-is-even-or-odd

wich exposes that "number & 1" might fail on "one complements" computers - and that "number % 2" could be optimized correctly by the final compiler then ...


And the thread there contains another funny option - recursion:

Function IsOdd:int(n:int)
   if n = 0
      return 0
   elseif n = 1
      return 1
   else
      return not IsOdd(n - 1)
   endif
End Function



bye
Ron

RemiD

it seems that you have the topic for the next competition :
each participant much create 2 procedures to do something,
one very optimized and minimalist (and fast)
one very bullshity and bulky (and slow)
;D