Check given number is prime number

Write a program to check if the given number is prime or not.

Prime Number: A number that is divisible by 1 and itself is a prime number.

Note: 1 is not a prime number.

Example:

Input: 13
Output13 is prime number
ExplanationIf number only divisible by 1 and itself then number is prime.

Approach: Iterate till n-1 if the number is divisible by any number then the number is not prime, else the number is prime.

C

#include <stdio.h>
int main()
{
    int n = 13;
    if (n <= 1)
        printf("Number is not prime ");
    else
    {
        int flag = 0;
        for (int i = 2i < ni++)
        {
            if (n % i == 0)
            {
                flag = 1;
                break;
            }
        }
        if (flag == 0)
        {
            printf("Number is prime ");
        }
        else
        {
            printf("Number is not prime ");
        }
    }
    return 0;
}

Java

public class CheckIsPrime{
     
  public static void main(String[] args) {
    int number=13;
    if(number>1 && checkIsPrime(number))
    System.out.println(number+" is prime number");
    else
    System.out.println(number+" is not prime number");
  }
//Method to check prime number
  private static boolean checkIsPrime(int number) {
    
    for(int i=2;i<number;i++)
       {
 // If a number is divisible by any number from 2 to n-1
 // then it is not a prime
        if(number%i==0)
           return false;
       }
     return true;
  }
}
//Time Complexity:O(n)
//Space Complexity:O(1)

C++

#include <bits/stdc++.h>
using namespace std;
//Function to check for prime numbers
bool checkPrime(int n)
{
  if(n==1)
    return false;
  for(int i=2;i<n;i++)
    {
  //If a number is divisible by
// any number from 2 to n-1
  // then it is not a prime
      if(n%i==0)
        return false;
     }
   return true;
}
int main()
{
   int n=13;
   if(checkPrime(n))
      cout<<n<<" is a prime\n";
   else
      cout<<n<<" is not a prime\n";
}

//Time Complexity :O(n)
//Space Complexity:O(1)


No comments:

Post a Comment