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: 13Output: 13 is prime numberExplanation: If 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 = 2; i < n; i++){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");elseSystem.out.println(number+" is not prime number");}//Method to check prime numberprivate 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 primeif(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 numbersbool 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 primeif(n%i==0)return false;}return true;}int main(){int n=13;if(checkPrime(n))cout<<n<<" is a prime\n";elsecout<<n<<" is not a prime\n";}//Time Complexity :O(n)//Space Complexity:O(1)
No comments:
Post a Comment