search
HomeBackend DevelopmentC++Abominable numbers

Abominable numbers

Aug 31, 2023 pm 07:41 PM
programmingnumberAbominable

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
Output: Non-Odious Number

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
Output: Odious Number

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
Output: Non-Odious Number

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
  • 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;
}

Output

27 is Non-Odious Number

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)

Loop iteration 2 -

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

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;
}

Output

27 is Non-Odious Number

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
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
XML in C  : Handling Complex Data StructuresXML in C : Handling Complex Data StructuresMay 02, 2025 am 12:04 AM

Working with XML data structures in C can use the TinyXML or pugixml library. 1) Use the pugixml library to parse and generate XML files. 2) Handle complex nested XML elements, such as book information. 3) Optimize XML processing code, and it is recommended to use efficient libraries and streaming parsing. Through these steps, XML data can be processed efficiently.

C   and Performance: Where It Still DominatesC and Performance: Where It Still DominatesMay 01, 2025 am 12:14 AM

C still dominates performance optimization because its low-level memory management and efficient execution capabilities make it indispensable in game development, financial transaction systems and embedded systems. Specifically, it is manifested as: 1) In game development, C's low-level memory management and efficient execution capabilities make it the preferred language for game engine development; 2) In financial transaction systems, C's performance advantages ensure extremely low latency and high throughput; 3) In embedded systems, C's low-level memory management and efficient execution capabilities make it very popular in resource-constrained environments.

C   XML Frameworks: Choosing the Right One for YouC XML Frameworks: Choosing the Right One for YouApr 30, 2025 am 12:01 AM

The choice of C XML framework should be based on project requirements. 1) TinyXML is suitable for resource-constrained environments, 2) pugixml is suitable for high-performance requirements, 3) Xerces-C supports complex XMLSchema verification, and performance, ease of use and licenses must be considered when choosing.

C# vs. C  : Choosing the Right Language for Your ProjectC# vs. C : Choosing the Right Language for Your ProjectApr 29, 2025 am 12:51 AM

C# is suitable for projects that require development efficiency and type safety, while C is suitable for projects that require high performance and hardware control. 1) C# provides garbage collection and LINQ, suitable for enterprise applications and Windows development. 2)C is known for its high performance and underlying control, and is widely used in gaming and system programming.

How to optimize codeHow to optimize codeApr 28, 2025 pm 10:27 PM

C code optimization can be achieved through the following strategies: 1. Manually manage memory for optimization use; 2. Write code that complies with compiler optimization rules; 3. Select appropriate algorithms and data structures; 4. Use inline functions to reduce call overhead; 5. Apply template metaprogramming to optimize at compile time; 6. Avoid unnecessary copying, use moving semantics and reference parameters; 7. Use const correctly to help compiler optimization; 8. Select appropriate data structures, such as std::vector.

How to understand the volatile keyword in C?How to understand the volatile keyword in C?Apr 28, 2025 pm 10:24 PM

The volatile keyword in C is used to inform the compiler that the value of the variable may be changed outside of code control and therefore cannot be optimized. 1) It is often used to read variables that may be modified by hardware or interrupt service programs, such as sensor state. 2) Volatile cannot guarantee multi-thread safety, and should use mutex locks or atomic operations. 3) Using volatile may cause performance slight to decrease, but ensure program correctness.

How to measure thread performance in C?How to measure thread performance in C?Apr 28, 2025 pm 10:21 PM

Measuring thread performance in C can use the timing tools, performance analysis tools, and custom timers in the standard library. 1. Use the library to measure execution time. 2. Use gprof for performance analysis. The steps include adding the -pg option during compilation, running the program to generate a gmon.out file, and generating a performance report. 3. Use Valgrind's Callgrind module to perform more detailed analysis. The steps include running the program to generate the callgrind.out file and viewing the results using kcachegrind. 4. Custom timers can flexibly measure the execution time of a specific code segment. These methods help to fully understand thread performance and optimize code.

How to use the chrono library in C?How to use the chrono library in C?Apr 28, 2025 pm 10:18 PM

Using the chrono library in C can allow you to control time and time intervals more accurately. Let's explore the charm of this library. C's chrono library is part of the standard library, which provides a modern way to deal with time and time intervals. For programmers who have suffered from time.h and ctime, chrono is undoubtedly a boon. It not only improves the readability and maintainability of the code, but also provides higher accuracy and flexibility. Let's start with the basics. The chrono library mainly includes the following key components: std::chrono::system_clock: represents the system clock, used to obtain the current time. std::chron

See all articles

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use