Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
1.00/5 (6 votes)
See more:
Hi guys

I want to the ask a question for the brain burning ;-P

Write a function for decide about the odd or even numbers, this function should get a number and return "Number is odd" or "Number is even", with out the using any condition .....

Best Regards.
Homay
Posted
Comments
nv3 10-Sep-13 6:54am    
Take a look at how numbers are being represented in the binary system and the answer will be very obvious.
pasztorpisti 10-Sep-13 9:04am    
A number is odd only if its least significant bit (whose value is (2^0)==1) is set, all the other bits (2^1, 2^2,...) are even so their sum is also even. You can get the value of this bit with the following expressions: (number % 2) OR (number & 1). Most compilers optimize (number % 2) to (number & 1) that is usually faster on most machines, integer remainder with a divisor that is a power of 2 can always be reduced into and & instruction.

C++
const char * myBrainHurts(int n)
{
  static const char * ans[] = {"Number is even", "Number is odd" };
  return ans[n % 2];
}
 
Share this answer
 
This should do:
C++
#include <iostream>
const char* foo() {
   int some_number;
   std::cout << "please enter number!" << std::endl;
   std::cin >> some_number;
   return "Number is odd";
}

(note that there was no requirement to link the output to the input in any way! ;-p )
 
Share this answer
 
Comments
CPallini 10-Sep-13 7:59am    
OK, but it should anyway provide all the output range :-D
Aydin Homay 10-Sep-13 8:14am    
Good job guys
Stefan_Lang 10-Sep-13 8:58am    
You mean I should return "Number is odd or even"? ;-)
CPallini 10-Sep-13 9:23am    
Or...Both! :-D
C#
public string EvenOrOdd(int num)
        {
            string[] array2 = new string[] { "Even", "Odd" };

            num = num % 2;
            return ("Entered number is  " + array2[num]);
        }
 
Share this answer
 
even-or-odd-without-using-condtional-statement/[^]

Hope it is helpful enough...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900