Skip to main content

Featured

C Program to Check Prime Number Using Efficient Logic

  Introduction A prime number is a number that has exactly two distinct positive divisors: 1 and itself. In this program, we check whether a given number is prime or not using a simple and efficient logic. This type of program is commonly used in mathematics, competitive programming, and basic algorithm learning for beginners in C programming. Problem Statement The task is to write a C program that determines whether a given integer is a prime number or not. The program takes a single integer input from the user and analyzes its divisibility. If the number has no divisors other than 1 and itself, it should be identified as a prime number; otherwise, it is not prime. This problem is important in number theory and has practical relevance in areas such as cryptography, data validation, and algorithm design.  Algorithm / Logic Explanation To check whether a number is prime, we need to verify that it is not divisible by any number other than 1 and itself. The algorithm follows a si...

C program to check whether a given number is a power of 2 using bitwise operations

Check Power of 2 in C

⚡ Check If a Number Is a Power of 2

#include<stdio.h>

int power(int num)
{
    if(num > 0 && (num & (num - 1)) == 0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int main()
{
    int num;
    scanf("%d", &num);
    
    if(power(num))
    {
        printf("%d is a power of 2\n", num);
    }
    else
    {
        printf("%d is not a power of 2\n", num);
    }
}
  

๐Ÿ“˜ Explanation:

✅ The condition (num & (num - 1)) == 0 is true only if there is only one set bit in num.
✅ This logic efficiently checks whether a number is a power of 2.
✅ It excludes 0 and negative numbers.

๐Ÿงช Sample Output:

Input:
8
Output:
8 is a power of 2
    

๐Ÿท️ Keywords:

C program power of 2, bitwise check power of 2, efficient logic, beginner C programming, technical interview questions

Comments

Popular Posts

๐ŸŒ™