Jump to content

_IsOddEven


LurchMan
 Share

Recommended Posts

Hey everyone -

I was recently working on a program and I needed to figure out if a number was an odd or even number and after I figured out how to determine this I figured I would share it here in case someone else came across this.

Code and example:

$rtn = _IsOddEven (1)
ConsoleWrite($rtn & @CRLF)
$rtn = _IsOddEven (2)
ConsoleWrite($rtn & @CRLF)
$rtn = _IsOddEven (15987)
ConsoleWrite($rtn & @CRLF)
$rtn = _IsOddEven (15896)
ConsoleWrite($rtn & @CRLF)
$rtn = _IsOddEven ("h15896")
ConsoleWrite($rtn & @CRLF)

Func _IsOddEven ($iNum)
    If Not Number ($iNum) Then Return -1
    $iNum = Number (StringRight($iNum, 1))
    For $iTest = 1 To $iNum+5 Step 2
        If $iNum = $iTest Then Return "Odd"
    Next
    For $iTest = 2 To $iNum+5 Step 2
        If $iNum = $iTest Then Return "Even"
    Next
    Return -1
EndFunc

Its fairly simple - Returns either Odd or Even, or -1 if it is not even a number.

(If someone has already done this then just ignore me. I did a quick search and couldn't find anything for it.)

Dating a girl is just like writing software. Everything's going to work just fine in the testing lab (dating), but as soon as you have contract with a customer (marriage), then your program (life) is going to be facing new situations you never expected. You'll be forced to patch the code (admit you're wrong) and then the code (wife) will just end up all bloated and unmaintainable in the end.

Link to comment
Share on other sites

Nice, adding to my Function Folder!

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Nice, adding to my Function Folder!

Thank you!

Dating a girl is just like writing software. Everything's going to work just fine in the testing lab (dating), but as soon as you have contract with a customer (marriage), then your program (life) is going to be facing new situations you never expected. You'll be forced to patch the code (admit you're wrong) and then the code (wife) will just end up all bloated and unmaintainable in the end.

Link to comment
Share on other sites

I use this:

#include <Misc.au3> ;only for _Iif() function - to check conditions

$iNumber = 123456789

$iIsEven = _NumberIsEven($iNumber)

If @error Then
    MsgBox(48, "Even check", "<" & $iNumber & "> is not a number.")
Else
    $sMessage = _Iif($iIsEven, "an Even number", "not an Even number (it is Odd)")
    MsgBox(64, "Even check", "The given number <" & $iNumber & "> is " & $sMessage)
EndIf

Func _NumberIsEven($iNumString)
    If Not StringIsDigit($iNumString) Then
        Return SetError(1, 0, -1)
    EndIf
    
    Return Number(Mod(Number($iNumString), 2) = 0)
EndFunc

It's a proper way to check even number.

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Hmm, didn't think this would deserve a function:

BitAND($iVal,1)
Link to comment
Share on other sites

I honestly don't know what the BitAnd or Mod functions do. I'm still fairly new to programing.

Dating a girl is just like writing software. Everything's going to work just fine in the testing lab (dating), but as soon as you have contract with a customer (marriage), then your program (life) is going to be facing new situations you never expected. You'll be forced to patch the code (admit you're wrong) and then the code (wife) will just end up all bloated and unmaintainable in the end.

Link to comment
Share on other sites

BitAND returns any bits that are in the first number AND the second, hence the name. In this case, the second has only one bit set. This checks if that bit is set in this case. To understand that, you'll need to understand binary, do some reading - As a simple explanation though: since the bits go 1,2,4,8,16 ... the first bit will always be set for an odd number.

Number: 00101010 (42)
BitAnd: 00000001 (1)
Result: 00000000 (0)

Number: 00101011 (43)
BitAnd: 00000001 (1)
Result: 00000000 (1)

Edit: Also remember that it's right to left in terms of bits... So the first bit is in fact the 8th from the left. It may sound stupid, but it works exactly the same way with normal numbers.

Mod on the other hand is basically the remainder like you learnt it in primary school. 9 / 2 is 4 remainder 1, Likewise Mod(9, 2) returns 1.

On computers, using the bitwise functions (AND, NOT, OR, XOR ... ) should be the fastest way.

Edited by Mat
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...