Evil Number with Example in C++


In this problem, we are given an array a number N. Our task is to check whether the number is an evil Number or Odious Number. 

Evil Number: It is a positive number which has an even number of 1’s in its binary expansion.

Example: 5, 17

Odious Number: It is a positive number which has an odd number of 1’s in its binary expansion.

example : 4, 6

Let’s take an example to understand the problem,

Input: N = 65

Output: Evil Number

Explanation: 

Binary Expansion of 65 :  1000001

Solution Approach: 

A simple solution to the problem is by finding the binary expansion of the number and then counting the number of 1’s in the expansion. If the count is even the number is an evil number otherwise it is an Odious number. 

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
using namespace std;

int isEvilNumber(int n) {

   int count = 0;
   while (n != 0) {
      int r = n % 2;
      if(r == 1)
         count++;
      n = n / 2;
   }
   
   if (count % 2 == 0)
      return 1;
   else
      return 0;
}

int main(void)
{
   int num = 2049;
   if (isEvilNumber(num) )
      cout<<"The number "<<num<<" is an Evil Number";
   else
      cout<<"The number "<<num<<" is an Odious Number";
   return 0;
}

Output −

The number 2049 is an Evil Number

Updated on: 22-Jan-2021

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements