Tuesday, July 28, 2009

In computer programming how do you know whether a digit is even or odd?

In computer programming how do you know whether a digit is even or odd?





I'm doing a flowchart that finds the factor/s of a given number.

In computer programming how do you know whether a digit is even or odd?
suppose u have a number "num"


if the number is even it'll be a multiple of 2 and leave 0 as the remainder wen divided by 2 .. so in C++ language


if (num%2==0)


//the no. is even else it is no


note: the operator % is c++ gives u the remainder of the division ..


but i have a query .. ur doing a flowchart on factors of a number so y do u want to know whether the number is even or odd ..


all u need to do is run a loop from one to the number ..


n find the remainder in each loop by dividing the loop element by the number, if the remainder is 0 .. the loop element is a factor of the number ..


in technical language ..


for(int i=1;i%26lt;num;i++)


{


if(num%i==0)


{ i is a factor


}


else


{


i is not a factor


}


}
Reply:The modulus of the number divided by 2.





If this is 1 then it's odd, if it's 0 then it's even.





i.e. in a c-style language:





if (x % 2 == 1) {


// odd


}


else if (x % 2 == 0) {


//even


}
Reply:Divide it by 2 and look at the remainder - if the remainder is 1, or fractional 1/2, then the original number was odd - if there is no remainder, then it is even.





Most languages have some function that will do this for you though (e.g. php has is_even(x) / is_odd(x))





--edit-- ignore the php functions - something I've just checked php.com and I'm wrong, but the original answer still stands





--edit 2-- just seen you are working with factors - checking to see if a number has a remainder of 0 means it is a factor - this will work with all numbers, not just 2.
Reply:LSB = 0 means that number is even


LSB = 1 means that number is odd
Reply:every odd number has a reminder when you divide the odd number with 2.


9/2 reminder =1


3/2 reminder=1


97/2 reminder =1
Reply:If you get the mod 2 of the digit (% 2 in Java) it will return the remainder of the digit/2. Even number will have this as 0. Odd number will have this as non-0, or 1.
Reply:To find out if a number is even or odd, just use n%2==0. This will return true if it is even, odd if it is not. To take a specific digit out of a number, do this, if m is the number and n is the digit, with 0 being the ones, 1 being the tens, and so on...





digit = (m%(10^(n+1)))/(10^n)





Good luck!
Reply:Check to see if modulus 2 is 0.


e.g. if (x%2==0)


even = true


else


even = false


No comments:

Post a Comment