Print numbers having first and last bits as the only set bits

The task is to print numbers that have exactly two set bits: one at the first (rightmost) position and one at the last (leftmost) position. These numbers follow the pattern where only the most significant bit and the least significant bit are set to 1.

Set bits are binary digits with value 1, while unset bits have value 0. Numbers with first and last bits set follow the pattern: 1, 3 (11), 5 (101), 9 (1001), 17 (10001), etc.

Syntax

// Check if number has only first and last bits set
if (!(n-1 & n-2))
    // n has the required pattern

Algorithm

START Initialize num=5, i=1 Print 1 Loop i=3 to num if (!(i-1 & i-2)) Print i END

Example

The following program prints numbers having only first and last bits set within a given range −

#include <stdio.h>

int main() {
    unsigned int num = 5;
    int i = 1;
    
    printf("Numbers with first and last bits set: ");
    printf("%d ", i); // Print first number 1
    
    for (i = 3; i <= num; ++i) {
        if (!(i-1 & i-2)) { // Check if only first and last bits are set
            printf("%d ", i);
        }
    }
    printf("<br>");
    
    return 0;
}

Output

Numbers with first and last bits set: 1 3 5

How It Works

The condition !(i-1 & i-2) works because:

  • For numbers with only first and last bits set: i-1 and i-2 have no common set bits
  • Example: For i=5 (101), i-1=4 (100), i-2=3 (011). Since 100 & 011 = 000, the condition is true
  • For other numbers, i-1 and i-2 share at least one set bit, making the AND operation non-zero

Extended Example

Here's an example that shows more numbers in the sequence −

#include <stdio.h>

int main() {
    unsigned int num = 20;
    int i = 1;
    
    printf("Numbers with first and last bits set up to %u: ", num);
    printf("%d ", i);
    
    for (i = 3; i <= num; ++i) {
        if (!(i-1 & i-2)) {
            printf("%d ", i);
        }
    }
    printf("<br>");
    
    return 0;
}

Output

Numbers with first and last bits set up to 20: 1 3 5 9 17

Conclusion

This algorithm efficiently identifies numbers with exactly two set bits at the first and last positions using bitwise operations. The pattern generates powers of 2 plus 1: 1, 3, 5, 9, 17, etc.

Updated on: 2026-03-15T11:06:54+05:30

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements