Segregate Prime and Non-Prime Numbers in an array
Last Updated :
06 Jul, 2023
Given an array arr[] of size N, the task is to rearrange the array elements such that all the Prime numbers are placed before the Non-prime numbers.
Examples:
Input: arr[] = {1, 8, 2, 3, 4, 5, 7, 20}
Output: 7 5 2 3 4 8 1 20
Explanation:
The output consists of all the prime numbers 7 5 2 3, followed by Non-Prime numbers 4 8 1 20.
Input: arr[] = {2, 3, 4, 5, 6, 7, 8, 9, 10}
Output: 2 3 7 5 6 4 8 9 10
Naive Approach:
The simplest approach to solve this problem is to make two arrays/vectors to store the prime and non-prime array elements respectively and print the prime numbers followed by the non-primes numbers.
Steps to implement this approach:
- Make two vector prime and nonPrime to store prime and non-prime numbers
- After that traverse the whole input array and if any number is prime then push that into the prime vector else into the nonPrime vector
- To check if any number is prime or not, we will take care of many edge cases like 0,1 is not prime, 2,3 is prime, etc..
- In the last first print elements of the prime vector then print elements of the nonPrime vector
Code to implement the above steps:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if a number n
// is a prime number of not
bool isPrime(int n)
{
// Edges Cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// To skip middle five numbers
if (n % 2 == 0 || n % 3 == 0)
return false;
// Checks for prime or non prime
for (int i = 5;
i * i <= n; i = i + 6) {
// If n is divisible by i
// or i + 2, return false
if (n % i == 0
|| n % (i + 2) == 0)
return false;
}
// Otherwise, the
// number is prime
return true;
}
// Function to segregate the primes
// and non-primes present in an array
void segregatePrimeNonPrime(
int arr[], int N)
{
//To store Prime Numbers
vector<int> prime;
//To store non-prime numbers
vector<int> nonPrime;
//Traverse the input array
for(int i=0;i<N;i++){
if(isPrime(arr[i])){prime.push_back(arr[i]);}
else{nonPrime.push_back(arr[i]);}
}
//First print all prime numbers
for(int i=0;i<prime.size();i++){
cout<<prime[i]<<" ";
}
//After printing all prime numbers print all non-prime numbers
for(int i=0;i<nonPrime.size();i++){
cout<<nonPrime[i]<<" ";
}
}
// Driver Code
int main()
{
int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 };
int N = sizeof(arr) / sizeof(arr[0]);
segregatePrimeNonPrime(arr, N);
return 0;
}
Java
import java.util.*;
public class Main
{
// Function to check if a number n
// is a prime number of not
public static boolean isPrime(int n)
{
// Edges Cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// To skip middle five numbers
if (n % 2 == 0 || n % 3 == 0)
return false;
// Checks for prime or non prime
for (int i = 5; i * i <= n; i = i + 6) {
// If n is divisible by i
// or i + 2, return false
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
// Otherwise, the
// number is prime
return true;
}
// Function to segregate the primes
// and non-primes present in an array
public static void segregatePrimeNonPrime(int[] arr,
int N)
{
// To store Prime Numbers
ArrayList<Integer> prime = new ArrayList<Integer>();
// To store non-prime numbers
ArrayList<Integer> nonPrime
= new ArrayList<Integer>();
// Traverse the input array
for (int i = 0; i < N; i++) {
if (isPrime(arr[i])) {
prime.add(arr[i]);
}
else {
nonPrime.add(arr[i]);
}
}
// First print all prime numbers
for (int i = 0; i < prime.size(); i++) {
System.out.print(prime.get(i) + " ");
}
// After printing all prime numbers print all
// non-prime numbers
for (int i = 0; i < nonPrime.size(); i++) {
System.out.print(nonPrime.get(i) + " ");
}
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 2, 3, 4, 6, 7, 8, 9, 10 };
int N = arr.length;
segregatePrimeNonPrime(arr, N);
}
}
Python3
# Python program for the above approach
import math
# Function to check if a number n is a prime number of not
def isPrime(n):
# Edges Cases
if n <= 1:
return False
if n <= 3:
return True
# To skip middle five numbers
if n % 2 == 0 or n % 3 == 0:
return False
# Checks for prime or non prime
for i in range(5, int(math.sqrt(n)) + 1, 6):
# If n is divisible by i or i + 2, return false
if n % i == 0 or n % (i + 2) == 0:
return False
# Otherwise, the number is prime
return True
# Function to segregate the primes and non-primes present in an array
def segregatePrimeNonPrime(arr, N):
# To store Prime Numbers
prime = []
# To store non-prime numbers
nonPrime = []
# Traverse the input array
for i in range(N):
if isPrime(arr[i]):
prime.append(arr[i])
else:
nonPrime.append(arr[i])
# First print all prime numbers
for i in range(len(prime)):
print(prime[i], end=" ")
# After printing all prime numbers print all non-prime numbers
for i in range(len(nonPrime)):
print(nonPrime[i], end=" ")
# Driver Code
if __name__ == '__main__':
arr = [2, 3, 4, 6, 7, 8, 9, 10]
N = len(arr)
segregatePrimeNonPrime(arr, N)
C#
using System;
using System.Collections.Generic;
public class MainClass
{
// Function to check if a number n
// is a prime number of not
public static bool IsPrime(int n)
{
// Edge Cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// To skip middle five numbers
if (n % 2 == 0 || n % 3 == 0)
return false;
// Checks for prime or non prime
for (int i = 5; i * i <= n; i = i + 6)
{
// If n is divisible by i
// or i + 2, return false
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
// Otherwise, the
// number is prime
return true;
}
// Function to segregate the primes
// and non-primes present in an array
public static void SegregatePrimeNonPrime(int[] arr, int N)
{
// To store Prime Numbers
List<int> prime = new List<int>();
// To store non-prime numbers
List<int> nonPrime = new List<int>();
// Traverse the input array
for (int i = 0; i < N; i++)
{
if (IsPrime(arr[i]))
{
prime.Add(arr[i]);
}
else
{
nonPrime.Add(arr[i]);
}
}
// First print all prime numbers
for (int i = 0; i < prime.Count; i++)
{
Console.Write(prime[i] + " ");
}
// After printing all prime numbers print all
// non-prime numbers
for (int i = 0; i < nonPrime.Count; i++)
{
Console.Write(nonPrime[i] + " ");
}
}
// Driver Code
public static void Main(string[] args)
{
int[] arr = { 2, 3, 4, 6, 7, 8, 9, 10 };
int N = arr.Length;
SegregatePrimeNonPrime(arr, N);
}
}
JavaScript
<script>
// Javascript program for the above approach
// Function to check if a number n
// is a prime number of not
function isPrime(n) {
// Edges Cases
if (n <= 1) {
return false;
}
if (n <= 3) {
return true;
}
// To skip middle five numbers
if (n % 2 === 0 || n % 3 === 0) {
return false;
}
// Checks for prime or non prime
for (let i = 5; i * i <= n; i += 6) {
// If n is divisible by i
// or i + 2, return false
if (n % i === 0 || n % (i + 2) === 0) {
return false;
}
}
// Otherwise, the
// number is prime
return true;
}
// Function to segregate the primes
// and non-primes present in an array
function segregatePrimeNonPrime(arr) {
//To store Prime Numbers
let prime = [];
//To store non-prime numbers
let nonPrime = [];
//Traverse the input array
for (let i = 0; i < arr.length; i++) {
if (isPrime(arr[i])) {
prime.push(arr[i]);
} else {
nonPrime.push(arr[i]);
}
}
//First print all prime numbers
for (let i = 0; i < prime.length; i++) {
document.write(prime[i] + " ");
}
//After printing all prime numbers print all non-prime numbers
for (let i = 0; i < nonPrime.length; i++) {
document.write(nonPrime[i] + " ");
}
}
// Driver Code
let arr = [2, 3, 4, 6, 7, 8, 9, 10];
segregatePrimeNonPrime(arr);
// This code is contributed by Pushpesh Raj
</script>
Output-
2 3 7 4 6 8 9 10
Time Complexity: O(N*sqrt(N)), O(N) for traversing the array, and sqrt(N) for finding whether any number is prime or not.
Auxiliary Space: O(N),because of prime and nonPrime vector
Alternate Approach: To optimize the auxiliary space of the above approach, the idea to solve this problem is using the Two-Pointer Approach. Follow the steps below to solve the problem:
- Initialize two pointers left as 0 and right to the end of the array as (N - 1).
- Traverse the array until left is less than right and do the following:
- Keep incrementing the left pointer until the element pointing to the left index is Prime Number.
- Keep decrementing the right pointer until the element pointing to the left index is a non-Prime Number.
- If left is less than right then swap arr[left] and arr[right] and increment left and decrement right by 1.
- After the above steps, print the update array arr[].
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <iostream>
using namespace std;
// Function to swap two numbers a and b
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// Function to check if a number n
// is a prime number of not
bool isPrime(int n)
{
// Edges Cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// To skip middle five numbers
if (n % 2 == 0 || n % 3 == 0)
return false;
// Checks for prime or non prime
for (int i = 5;
i * i <= n; i = i + 6) {
// If n is divisible by i
// or i + 2, return false
if (n % i == 0
|| n % (i + 2) == 0)
return false;
}
// Otherwise, the
// number is prime
return true;
}
// Function to segregate the primes
// and non-primes present in an array
void segregatePrimeNonPrime(
int arr[], int N)
{
// Initialize left and right pointers
int left = 0, right = N - 1;
// Traverse the array
while (left < right) {
// Increment left while array
// element at left is prime
while (isPrime(arr[left]))
left++;
// Decrement right while array
// element at right is non-prime
while (!isPrime(arr[right]))
right--;
// If left < right, then swap
// arr[left] and arr[right]
if (left < right) {
// Swap arr[left] and arr[right]
swap(&arr[left], &arr[right]);
left++;
right--;
}
}
// Print segregated array
for (int i = 0; i < N; i++)
cout << arr[i] << " ";
}
// Driver Code
int main()
{
int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 };
int N = sizeof(arr) / sizeof(arr[0]);
segregatePrimeNonPrime(arr, N);
return 0;
}
Java
// java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
public class GFG {
// Function to check if a number n
// is a prime number of not
static boolean isPrime(int n)
{
// Edges Cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// To skip middle five numbers
if (n % 2 == 0 || n % 3 == 0)
return false;
// Checks for prime or non prime
for (int i = 5; i * i <= n; i = i + 6) {
// If n is divisible by i
// or i + 2, return false
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
// Otherwise, the
// number is prime
return true;
}
// Function to segregate the primes
// and non-primes present in an array
static void segregatePrimeNonPrime(int arr[], int N)
{
// Initialize left and right pointers
int left = 0, right = N - 1;
// Traverse the array
while (left < right) {
// Increment left while array
// element at left is prime
while (isPrime(arr[left]))
left++;
// Decrement right while array
// element at right is non-prime
while (!isPrime(arr[right]))
right--;
// If left < right, then swap
// arr[left] and arr[right]
if (left < right) {
// Swap arr[left] and arr[right]
int temp = arr[right];
arr[right] = arr[left];
arr[left] = temp;
left++;
right--;
}
}
// Print segregated array
for (int i = 0; i < N; i++)
System.out.print(arr[i] + " ");
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 };
int N = arr.length;
segregatePrimeNonPrime(arr, N);
}
}
// This code is contributed by Kingash.
Python3
# Python3 program for the above approach
# Function to check if a number n
# is a prime number of not
def isPrime(n):
# Edges Cases
if (n <= 1):
return False
if (n <= 3):
return True
# To skip middle five numbers
if (n % 2 == 0 or n % 3 == 0):
return False
# Checks for prime or non prime
i = 5
while (i * i <= n):
# If n is divisible by i or i + 2,
# return False
if (n % i == 0 or n % (i + 2) == 0):
return False
i += 6
# Otherwise, the number is prime
return True
# Function to segregate the primes and
# non-primes present in an array
def segregatePrimeNonPrime(arr, N):
# Initialize left and right pointers
left, right = 0, N - 1
# Traverse the array
while (left < right):
# Increment left while array element
# at left is prime
while (isPrime(arr[left])):
left += 1
# Decrement right while array element
# at right is non-prime
while (not isPrime(arr[right])):
right -= 1
# If left < right, then swap
# arr[left] and arr[right]
if (left < right):
# Swap arr[left] and arr[right]
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
# Print segregated array
for num in arr:
print(num, end=" ")
# Driver code
arr = [2, 3, 4, 6, 7, 8, 9, 10]
N = len(arr)
segregatePrimeNonPrime(arr, N)
# This code is contributed by girishthatte
C#
// C# program for the above approach
using System;
class GFG{
// Function to check if a number n
// is a prime number of not
static bool isPrime(int n)
{
// Edges Cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// To skip middle five numbers
if (n % 2 == 0 || n % 3 == 0)
return false;
// Checks for prime or non prime
for(int i = 5; i * i <= n; i = i + 6)
{
// If n is divisible by i
// or i + 2, return false
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
// Otherwise, the
// number is prime
return true;
}
// Function to segregate the primes
// and non-primes present in an array
static void segregatePrimeNonPrime(int[] arr, int N)
{
// Initialize left and right pointers
int left = 0, right = N - 1;
// Traverse the array
while (left < right)
{
// Increment left while array
// element at left is prime
while (isPrime(arr[left]))
left++;
// Decrement right while array
// element at right is non-prime
while (!isPrime(arr[right]))
right--;
// If left < right, then swap
// arr[left] and arr[right]
if (left < right)
{
// Swap arr[left] and arr[right]
int temp = arr[right];
arr[right] = arr[left];
arr[left] = temp;
left++;
right--;
}
}
// Print segregated array
for(int i = 0; i < N; i++)
Console.Write(arr[i] + " ");
}
// Driver Code
public static void Main(string[] args)
{
int[] arr = { 2, 3, 4, 6, 7, 8, 9, 10 };
int N = arr.Length;
segregatePrimeNonPrime(arr, N);
}
}
// This code is contributed by ukasp
JavaScript
<script>
// Javascript program implementation
// of the approach
// Function to generate prime numbers
// using Sieve of Eratosthenes
function SieveOfEratosthenes(prime, n)
{
for(let p = 2; p * p <= n; p++)
{
// If prime[p] is unchanged,
// then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for(let i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
// Function to segregate the primes and non-primes
function segregatePrimeNonPrime(prime, arr, N)
{
// Generate all primes till 10^
SieveOfEratosthenes(prime, 10000000);
// Initialize left and right
let left = 0, right = N - 1;
// Traverse the array
while (left < right)
{
// Increment left while array element
// at left is prime
while (prime[arr[left]])
left++;
// Decrement right while array element
// at right is non-prime
while (!prime[arr[right]])
right--;
// If left < right, then swap arr[left]
// and arr[right]
if (left < right)
{
// Swap arr[left] and arr[right]
let temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
// Print segregated array
for(let i = 0; i < N; i++)
document.write(arr[i] + " ");
}
// Driver Code
let prime = Array.from({length: 10000001}, (_, i) => true);
let arr = [ 2, 3, 4, 6, 7, 8, 9, 10 ];
let N = arr.length;
// Function Call
segregatePrimeNonPrime(prime, arr, N);
</script>
Time Complexity: O(N*sqrt(N))
Auxiliary Space: O(1), since no extra space has been taken.
Efficient Approach: The above approach can be optimized by using the Sieve of Eratosthenes to find whether the number is prime or non-prime in constant time.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
bool prime[10000001];
// Function to swap two numbers a and b
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// Function to generate prime numbers
// using Sieve of Eratosthenes
void SieveOfEratosthenes(int n)
{
memset(prime, true, sizeof(prime));
for (int p = 2; p * p <= n; p++) {
// If prime[p] is unchanged,
// then it is a prime
if (prime[p] == true) {
// Update all multiples of p
for (int i = p * p;
i <= n; i += p)
prime[i] = false;
}
}
}
// Function to segregate the primes
// and non-primes
void segregatePrimeNonPrime(
int arr[], int N)
{
// Generate all primes till 10^7
SieveOfEratosthenes(10000000);
// Initialize left and right
int left = 0, right = N - 1;
// Traverse the array
while (left < right) {
// Increment left while array
// element at left is prime
while (prime[arr[left]])
left++;
// Decrement right while array
// element at right is non-prime
while (!prime[arr[right]])
right--;
// If left < right, then swap
// arr[left] and arr[right]
if (left < right) {
// Swap arr[left] and arr[right]
swap(&arr[left], &arr[right]);
left++;
right--;
}
}
// Print segregated array
for (int i = 0; i < N; i++)
cout << arr[i] << " ";
}
// Driver code
int main()
{
int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
segregatePrimeNonPrime(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to generate prime numbers
// using Sieve of Eratosthenes
public static void SieveOfEratosthenes(boolean[] prime,
int n)
{
for(int p = 2; p * p <= n; p++)
{
// If prime[p] is unchanged,
// then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for(int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
// Function to segregate the primes and non-primes
public static void segregatePrimeNonPrime(boolean[] prime,
int arr[], int N)
{
// Generate all primes till 10^
SieveOfEratosthenes(prime, 10000000);
// Initialize left and right
int left = 0, right = N - 1;
// Traverse the array
while (left < right)
{
// Increment left while array element
// at left is prime
while (prime[arr[left]])
left++;
// Decrement right while array element
// at right is non-prime
while (!prime[arr[right]])
right--;
// If left < right, then swap arr[left]
// and arr[right]
if (left < right)
{
// Swap arr[left] and arr[right]
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
// Print segregated array
for(int i = 0; i < N; i++)
System.out.printf(arr[i] + " ");
}
// Driver code
public static void main(String[] args)
{
boolean[] prime = new boolean[10000001];
Arrays.fill(prime, true);
int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 };
int N = arr.length;
// Function Call
segregatePrimeNonPrime(prime, arr, N);
}
}
// This code is contributed by girishthatte
Python3
# Python3 program for the above approach
# Function to generate prime numbers
# using Sieve of Eratosthenes
def SieveOfEratosthenes(prime, n):
p = 2
while (p * p <= n):
# If prime[p] is unchanged,
# then it is a prime
if (prime[p] == True):
# Update all multiples of p
i = p * p
while (i <= n):
prime[i] = False
i += p
p += 1
# Function to segregate the primes and non-primes
def segregatePrimeNonPrime(prime, arr, N):
# Generate all primes till 10^7
SieveOfEratosthenes(prime, 10000000)
# Initialize left and right
left, right = 0, N - 1
# Traverse the array
while (left < right):
# Increment left while array element
# at left is prime
while (prime[arr[left]]):
left += 1
# Decrement right while array element
# at right is non-prime
while (not prime[arr[right]]):
right -= 1
# If left < right, then swap arr[left]
# and arr[right]
if (left < right):
# Swap arr[left] and arr[right]
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
# Print segregated array
for num in arr:
print(num, end = " ")
# Driver code
arr = [ 2, 3, 4, 6, 7, 8, 9, 10 ]
N = len(arr)
prime = [True] * 10000001
# Function Call
segregatePrimeNonPrime(prime, arr, N)
# This code is contributed by girishthatte
C#
// C# program for the above approach
using System;
class GFG{
// Function to generate prime numbers
// using Sieve of Eratosthenes
public static void SieveOfEratosthenes(bool[] prime,
int n)
{
for(int p = 2; p * p <= n; p++)
{
// If prime[p] is unchanged,
// then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for(int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
// Function to segregate the primes and non-primes
public static void segregatePrimeNonPrime(bool[] prime,
int []arr, int N)
{
// Generate all primes till 10^
SieveOfEratosthenes(prime, 10000000);
// Initialize left and right
int left = 0, right = N - 1;
// Traverse the array
while (left < right)
{
// Increment left while array element
// at left is prime
while (prime[arr[left]])
left++;
// Decrement right while array element
// at right is non-prime
while (!prime[arr[right]])
right--;
// If left < right, then swap arr[left]
// and arr[right]
if (left < right)
{
// Swap arr[left] and arr[right]
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
// Print segregated array
for(int i = 0; i < N; i++)
Console.Write(arr[i] + " ");
}
// Driver code
public static void Main(String[] args)
{
bool[] prime = new bool[10000001];
for(int i = 0; i < prime.Length; i++)
prime[i] = true;
int []arr = { 2, 3, 4, 6, 7, 8, 9, 10 };
int N = arr.Length;
// Function Call
segregatePrimeNonPrime(prime, arr, N);
}
}
// This code is contributed by Princi Singh
JavaScript
// Javascript program for the above approach
// Function to generate prime numbers
// using Sieve of Eratosthenes
function SieveOfEratosthenes(prime, n)
{
for(let p = 2; p * p <= n; p++)
{
// If prime[p] is unchanged,
// then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for(let i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
// Function to segregate the primes and non-primes
function segregatePrimeNonPrime(prime, arr, N)
{
// Generate all primes till 10^
SieveOfEratosthenes(prime, 10000000);
// Initialize left and right
let left = 0, right = N - 1;
// Traverse the array
while (left < right)
{
// Increment left while array element
// at left is prime
while (prime[arr[left]])
left++;
// Decrement right while array element
// at right is non-prime
while (!prime[arr[right]])
right--;
// If left < right, then swap arr[left]
// and arr[right]
if (left < right)
{
// Swap arr[left] and arr[right]
let temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
// Print segregated array
for(let i = 0; i < N; i++)
console.log(arr[i] + " ");
}
// Driver Code
let prime = Array.from({length: 10000001},
(_, i) => true);
let arr = [ 2, 3, 4, 6, 7, 8, 9, 10 ];
let N = arr.length;
// Function Call
segregatePrimeNonPrime(prime, arr, N);
Time Complexity: O(N*log(log(N)))
Auxiliary Space: O(N)
Similar Reads
Find prime number K in an array such that (A[i] % K) is maximum
Given an array arr[] of n integers. The task is to find an element from the array K such that K is prime.And, arr[i] % K is the maximum for all valid i among all possible values of K if there is no prime number in the array then print -1.Examples: Input: arr[] = {2, 10, 15, 7, 6, 8, 13} Output: 13 2
9 min read
C++ Program to Print Prime Numbers from 1 to n
A prime number is a natural number that has only two divisors, which are 1 and itself. In this article, we will learn how to print all the prime numbers from 1 to n in C++.ExamplesInput: n = 10Output: 2, 3, 5, 7Explanation: As 2, 3, 5, 7 are the only prime numbers between 1 to 10.Input: n = 5Output:
5 min read
C++ Program To Find Prime Numbers Between Given Interval
A prime number is defined as a natural number greater than 1 and is divisible by only 1 and itself. In other words, the prime number is a positive integer greater than 1 that has exactly two factors, 1 and the number itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 . . .Note: 1
7 min read
C Program To Find Prime Numbers Between Given Range
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, 7, and 11 are prime numbers. In this article, we will learn how to find all the prime numbers between the given range.ExampleInput: l = 10, r = 30Output: 11 13 17 19Explanat
6 min read
Sum of prime numbers in range [L, R] from given Array for Q queries
Given an array arr[] of the size of N followed by an array of Q queries, of the following two types: Query Type 1: Given two integers L and R, find the sum of prime elements from index L to R where 0 <= L <= R <= N-1.Query Type 2: Given two integers i and X, change arr[i] = X where 0 <=
15+ min read
Count numbers from range whose prime factors are only 2 and 3
Given two positive integers L and R, the task is to count the elements from the range [L, R] whose prime factors are only 2 and 3.Examples: Input: L = 1, R = 10 Output: 6 2 = 2 3 = 3 4 = 2 * 2 6 = 2 * 3 8 = 2 * 2 * 2 9 = 3 * 3Input: L = 100, R = 200 Output: 5 Approach: Start a loop from L to R and f
6 min read
Count all prime numbers in a given range whose sum of digits is also prime
Given two integers L and R, the task is to find the count of total numbers of prime numbers in the range [L, R] whose sum of the digits is also a prime number. Examples: Input: L = 1, R = 10 Output: 4 Explanation: Prime numbers in the range L = 1 to R = 10 are {2, 3, 5, 7}. Their sum of digits is {2
15 min read
C++ Program To Check If a Prime Number Can Be Expressed as Sum of Two Prime Numbers
Given a prime number N  . The task is to check if it is possible to express N  as sum of two separate prime numbers.Note: The range of N is less than 108. Examples: Input: N = 13 Output: Yes Explanation: The number 13 can be written as 11 + 2, here 11 and 2 are both prime. Input: N = 11 Output: No
2 min read
Count all the numbers in a range with smallest factor as K
Given a range of integer from 'a' to 'b' . Our task is to calculate the amount of numbers from the interval [ a, b ], that are not divisible by any number between 2 and k - 1 and yet divisible by k . Note : We do not have to consider a divisor equal to one.Examples: Input : a = 12, b = 23, k = 3 Out
11 min read
Find all possible ways to Split the given string into Primes
Given string str that represents a number. The task is to find all possible ways to split the given string such that each segment is a prime number in the range of 1 to 106.Examples: Input: str = "3175" Output: [317, 5] [31, 7, 5] [3, 17, 5]Explanation: There can be 8 possible ways to split: [3175]
10 min read