Categories
Class 11 Class 12

Evil Number ISC 2020 Specimen Practical

An evil number is a positive whole number which has even number of 1s in its binary equivalent.

Example:
Binary equivalent of 9 is 1001, which contains even number of 1s.
Thus, 9 is an evil number.

A few evil numbers are 3, 5, 6, 9, …

Design a program to accept a positive whole number ‘N’ where N > 2 and N < 100. Find the binary equivalent of the number and count the number of 1s in it and display whether it is an evil number or not with an appropriate message.

Test your program with the following data and some random data:

Example 1:
INPUT: N = 15
Binary equivalent = 1111
Number of 1s = 4
OUTPUT: EVIL NUMBER

Example 2:
N = 26
Binary equivalent = 11010
Number of 1s = 3
OUTPUT: NOT AN EVIL NUMBER

Example 3:
INPUT: N = 145
OUTPUT: NUMBER OUT OF RANGE

import java.io.*;
class Evil{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("N = ");
        int n = Integer.parseInt(br.readLine());
        if(n < 3 || n > 99){
            System.out.println("NUMBER OUT OF RANGE");
            return;
        }
        int bin = convert(n);
        int c = count(bin);
        System.out.println("Binary equivalent = " + bin);
        System.out.println("Number of 1s = " + c);
        if(c % 2 == 0)
            System.out.println("EVIL NUMBER");
        else
            System.out.println("NOT AN EVIL NUMBER");
    }
    public static int convert(int n){
        if(n <= 1)
            return n;
        else
            return convert(n / 2) * 10 + n % 2;
    }
    public static int count(int b){
        if(b <= 0)
            return 0;
        else if(b % 10 == 1)
            return 1 + count(b / 10);
        else
            return 0 + count(b / 10);
    }
}

Leave a Reply