Table of Contents
Problem Statement
Disgusting digital examples
illustrate
solution
Naive Approach
pseudocode
Example: C program
Output
Time and space analysis
Brian Kernighan’s Algorithmic Method
Example
Space-time analysis
Compare the above methods
in conclusion
Home Backend Development C++ Abominable numbers

Abominable numbers

Aug 31, 2023 pm 07:41 PM
programming number Abominable

Abominable numbers

A number is considered odd if it has an odd number of ones in its binary expansion. The first 10 odd numbers are 1,2,4,7,10,11,13,14,16,19,21. Interestingly, all powers of 2 are odd numbers because they only have 1 bit set.

The following article discusses in detail two methods of determining whether a number is a hateful number.

Problem Statement

The purpose of this question is to check if the given number is an abominable number, i.e. it is a positive number with an odd number of set bits in its binary expansion.

Disgusting digital examples

Input: 34
Copy after login
Output: Non-Odious Number
Copy after login
Copy after login

illustrate

The binary representation of

34 is 10010.

Set number of digits = 2.

Since the number of 1's is an even number, 34 is not a terrible number.

Input: 1024
Copy after login
Output: Odious Number
Copy after login

illustrate

The binary representation of

1024 is 10000000000.

Set number of digits = 1.

Since 1024 is a power of 2, there is only 1 setting bit. So it's a scary number.

Input: 53
Copy after login
Output: Non-Odious Number
Copy after login
Copy after login

illustrate

(53)10 = (110101)2

Set number of digits = 4.

Therefore, it is not an abominable number.

solution

In order to determine whether a number is hateful, we must know whether the number of digits set is an odd or even number. The main task here is to count the number of digits set in the binary expansion of a number. The following technique can be used to count the number of digits and then check whether the result is odd or even.

The Chinese translation of

Naive Approach

is:

Naive Approach

  • Use the loop and right shift operators to iterate through all the digits of the number one by one.

  • If the bit value is 1, increase the count by one.

  • Check whether the final value of count is odd or even.

  • Show answer.

pseudocode

Function no_of_set_bits()

  • Initialization count = 0

  • When (n > 0)

if ((n & 1) > 0)
   Increment count
Right Shift n
Copy after login
  • Return count

Function is_odious()

  • If (count is an odd number)

    • return true

  • other

    • Return error

Function main()

  • Initialization n

  • Function call no_of_set_bits()

  • Call function is_odious()

  • Print output

Example: C program

This program checks whether a number is offensive. It checks the rightmost bit in each iteration of the loop by shifting the value to the right by n at the end of each iteration in the function no_of_set_bits().

#include<iostream>
using namespace std;
// this function counts the number of set bits by analyzing the rightmost bit using a while loop till n > 0.
// it performs logical & operation between 1 and n to determine if the rightmost bit is set or not.
// if it is set, count is incremented by 1
// right shift the value of n to make the bit left of the rightmost bit, the new rightmost bit.
int no_of_set_bits(int n){
   int count = 0;
   while (n > 0){
   
      // if the rightmost bit is 1: increment count
      if ((n & 1) > 0){
         count++;
      }
      
      // right shift the value of n to examine the next bit
      n = n >> 1;
   }
   return count;
}
// this function determines if count of set bits is odd or even
// odd -> odious
bool is_odious(int count){

   // if count is odd return true
   if (count % 2 != 0){
      return true;
   }
   return false;
}

// main function
int main(){
   int n = 27;
   int countBits = no_of_set_bits(n);
   if (is_odious(countBits)){
      cout << n << " is Odious Number";
   }
   else {
      cout << n << " is Non-Odious Number";
   }
   return 0;
}
Copy after login

Output

27 is Non-Odious Number
Copy after login
Copy after login

Time and space analysis

Time complexity: O(log(n)), because binary expansion of n requires log2n bits, we check all bits to check which bits are set.

Space complexity: O(1), because no additional space is used.

Brian Kernighan’s Algorithmic Method

This algorithm can be used to calculate a set number of digits in a number in a more efficient way. The function is_odious() can then be used to determine whether the number is offensive.

The basic principle of this method is to repeatedly clear the rightmost set bit of the number while keeping track of how many iterations are needed to reach zero. The steps involved are -

  • Initialize count to 0

  • When the number is greater than zero, perform a bitwise & between the number and its 2's complement to unset the rightmost set bit.

  • The count is incremented with each loop iteration.

  • Check if the final count is odd.

  • Show results.

Example

Suppose the number is 10. The binary expansion of 10 is 1010. It can be observed that it has 2 setting bits.

Loop iteration 1 -

n = 10
n & (n-1) =  10 & 9
1010   (n)
1001   (n - 1)
1000   (n = 8)
Copy after login

Loop iteration 2 -

n = 8
n & (n-1) = 8 & 7
1000    (n)
0111	(n-1)
0       (n = 0) 
Copy after login

Number of iterations = number of settings = 2.

pseudocode

Function no_of_set_bits()

  • Initialization count = 0

  • When (n > 0)

    • n = n & (n-1)

      Increase count

  • Return count

Function is_odious()

    Same as previous method

Function main()

    Same as previous method

Example: C program

This program calculates the number of set bits by counting the number of iterations required to unset all bits. To cancel bits, we perform a bitwise AND operation on n and n-1. This is because the binary representation of n-1 flips n's rightmost set bit and all the bits that follow it.

#include<iostream>
using namespace std;
// this function counts the number of set bits by unsetting the rightmost set bit using a while loop till n > 0.
// it performs logical & operation between n and n - 1 to unset the rightmost set bit.
// count is incremented in every iteration
int no_of_set_bits(int n){
   int count = 0;
   while (n > 0){
      // update the value of n to unset the current rightmost set bit
      n = n & (n - 1);
      count++;
   }
   return count;
}

// this function determines if count of set bits is odd or even
// odd -> odious
bool is_odious(int count){

   // if count is odd return true
   if (count % 2 != 0){
      return true;
   }
   return false;
}

// main function
int main(){
   int n = 27;
   int countBits = no_of_set_bits(n); // function call
   if (is_odious(countBits)){
      cout << n << " is Odious Number";
   }
   else {
      cout << n << " is Non-Odious Number";
   }
   return 0;
}
Copy after login

Output

27 is Non-Odious Number
Copy after login
Copy after login

Space-time analysis

Time Complexity - O(log(x)), where x is the number of digits set in the number. If there is only 1 set bit, the loop will run once.

Space Complexity - O(1) because no extra space is used.

Compare the above methods

While the first approach is fairly easy to understand, it requires log(n) iterations to produce the final result. The second method, on the other hand, uses log(x) iteration, where x is the number of digits set in the binary expansion of the number. Therefore, it improves performance.

in conclusion

This article discusses two ways to check whether a number is objectionable. It also provides us with the concept of the method, examples, algorithms used, C program solutions, and complexity analysis of each method. It also compared the two methods to determine which was more effective.

The above is the detailed content of Abominable numbers. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Realme GT Neo6 is scheduled to be released on May 9th! The first AI digital human conference in the computer industry Realme GT Neo6 is scheduled to be released on May 9th! The first AI digital human conference in the computer industry May 08, 2024 pm 12:49 PM

On May 7, our mobile phone manufacturer officially announced that our company’s GTNeo6 launch conference is scheduled for May 9. GTNoe6 is positioned as a "performance storm", aiming to stir up the mid-range machine situation. In addition, this conference will also be the first AI digital human conference in the mobile phone industry. At that time, Realme Vice President, Global Marketing President, and China President Xu Qi will appear at the press conference in the form of a digital human. Digital man Xu Qi According to the official introduction, Realme GTNoe6, codenamed "Hurricane", is faster and stronger. It will challenge the strongest third-generation Snapdragon 8s flagship and the strongest product in its class. Recently, the Realme GTNeo6 was found to be directly on the e-commerce platform. Some core configurations were exposed, showing that the machine is not only equipped with a Snapdragon 8s processor, but also supports 120W flash charging.

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Unleash Your Inner Programmer: C for Absolute Beginners Unleash Your Inner Programmer: C for Absolute Beginners Oct 11, 2024 pm 03:50 PM

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

Collection of C++ programming puzzles: stimulate thinking and improve programming skills Collection of C++ programming puzzles: stimulate thinking and improve programming skills Jun 01, 2024 pm 10:26 PM

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values ​​of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Python Power, Simplified: A Beginner-Friendly Approach to Programming Python Power, Simplified: A Beginner-Friendly Approach to Programming Oct 11, 2024 pm 04:53 PM

Getting Started with Python Programming Install Python: Download and install from the official website. HelloWorld!: Use print("HelloWorld!") to print the first line of code. Practical case: Calculate the area of ​​a circle: Use π (3.14159) and the radius to calculate the area of ​​the circle. Variables and data types: Use variables to store data. Data types in Python include integers, floating point numbers, strings, and Boolean values. Expressions and assignments: Use operators to connect variables, constants, and functions, and use the assignment operator (=) to assign values ​​to variables. Control flow: if-else statement: execute different code blocks based on conditions, determine odd

Demystifying C: A Clear and Simple Path for New Programmers Demystifying C: A Clear and Simple Path for New Programmers Oct 11, 2024 pm 10:47 PM

C is an ideal choice for beginners to learn system programming. It contains the following components: header files, functions and main functions. A simple C program that can print "HelloWorld" needs a header file containing the standard input/output function declaration and uses the printf function in the main function to print. C programs can be compiled and run by using the GCC compiler. After you master the basics, you can move on to topics such as data types, functions, arrays, and file handling to become a proficient C programmer.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles