0% found this document useful (0 votes)
187 views67 pages

Primality Testing and Algorithms

The document discusses prime numbers and various methods for primality testing, highlighting their importance in mathematics, cryptography, and computer science. It covers algorithms for checking if a number is prime, including naive methods, efficient solutions, and the Sieve of Eratosthenes, along with interesting properties of prime numbers. Additionally, it addresses problems related to prime numbers, such as finding ideal arrays and prime factorization.

Uploaded by

siddh tyagi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
187 views67 pages

Primality Testing and Algorithms

The document discusses prime numbers and various methods for primality testing, highlighting their importance in mathematics, cryptography, and computer science. It covers algorithms for checking if a number is prime, including naive methods, efficient solutions, and the Sieve of Eratosthenes, along with interesting properties of prime numbers. Additionally, it addresses problems related to prime numbers, such as finding ideal arrays and prime factorization.

Uploaded by

siddh tyagi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Unit II - Primality Testing

Prime Numbers

 A prime number is a whole number greater than 1, which is


only divisible by 1 and itself.
 First few prime numbers are : 2, 3, 5, 7, 11, 13, 17, 19, 23 …..

Primality Test

 Algorithm for determining whether an input number is prime


Primality Testing (Use case)
Plays crucial role in mathematics and computer science

Used in Cryptography (RSA Encryption Algorithm) and Information Security

Used in Hashing Algorithm (Converting large data sets into smaller ones)

Utilized in Error Correcting Codes

Helps us to create Digital Signatures


Hashing Technique and
Prime Number
Prime numbers play a crucial role in hashing techniques, especially in designing
hash functions and hash tables.

Hash functions use prime number as a modulus to ensure uniform distribution


and to avoid collisions

Primality testing helps to verify that the chosen number is prime [Especially,
when large primes are needed].

Example: Before using p = 104729 in h(x) = x mod p, we’d use a primality test like
Miller–Rabin to confirm it's prime
Some interesting fact about Prime numbers

 2 is the only even Prime number.


 Every prime number can represented in form of 6n+1 or 6n-1,
where n is natural number.
 2, 3 are only two consecutive natural numbers which are prime
too.
 Every even integer greater than 2 can be expressed as the sum
of two primes (Goldbach Conjecture)
Some interesting fact about Prime numbers

 If n is a prime number, then for every a, 1 <= a < n,


an-1 ≡ 1 (mod n)
OR
an-1 % n = 1 (Fermat’s Little Theorem)
How do we check whether a number is Prime or not?

1. Naive solution
Iterate through all numbers from 2 to n-1 and for every number
check if it divides n
static boolean isPrime(int n)
{
// Corner case
if (n <= 1)
return false;

// Check from 2 to n-1


for (int i = 2; i < n; i++)
if (n % i == 0)
return false;

return true;
} Time complexity :O(n)
How do we check whether a number is Prime or not?

2. Efficient solutions

O(sqrt(n)) method: Instead of checking till n, we can check till √n because a


larger factor of n must be a multiple of smaller factor that has been already
checked

A trial division to test the primality of 100


Divisors of 100: 2, 4, 5, 10, 20, 25, 50
Largest factor is 100/2 = 50
All divisors of n are less than or equal to n/2
Some of divisors are redundant
Once we reach 10, which is √100, the divisors just flip around and repeat
How do we check whether a number is Prime or not?

3. More optimized solution

Every natural number can be represented as 6k + i for i=


0,1,2,3,4,5

All primes are of the form 6k ± 1, with the exception of 2 and 3.


So, check through all the numbers of form 6k ± 1 only.

PTO
How do we check whether a number is Prime or not?

static boolean isPrime(int n)


{
// Corner cases
if (n <= 1) return false;
if (n <= 3) return true;

// This is checked so that we can skip


// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0) return false;

for (int i = 5; i * i <= n; i = i + 6)


if (n % i == 0 || n % (i + 2) == 0)
return false;

return true;
}
Time complexity :O(√n)
PROBLEM-:Full Prime Number (prime number whose digits are also prime,e.g 23,53,73)

class Prime{

// function to check digits


public static boolean checkDigits(int n)
{
// check all digits are prime or not
while (n > 0) {
int dig = n % 10;

// check if digits are prime or not


if (dig != 2 && dig != 3 &&
dig != 5 && dig != 7)
return false;

n /= 10;
}
return true;
}

// To check if n is prime or not


public static boolean prime(int n) Limitation:
{  Inefficient for Large Numbers
if (n == 1)
 Unsuitable for Very Small Numbers
return false;
 No Optimization for Known Primes
// check for all factors
 Limited Scalability
// Uses the square root method
 No Certainty for Probabilistic Primality
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
// To check if n is Full Prime
public static boolean isFullPrime(int n)
{
// The order is important here for
// efficiency
return (checkDigits(n) && prime(n));
}

// driver code
public static void main(String[] args)
{
int n = 53;
if (isFullPrime(n))
[Link]( "Yes" );
else
[Link]( "No");
}
}
How do we check whether a number is Prime or not?

Problem (2) Fermat’s Little Theorem:

If n is a prime number, then for every a, 1 <= a < n,


an-1 ≡ 1 (mod n)
OR
an-1 % n = 1
e.g. Since 7 is prime,
26 ≡ 1 (mod 7),
36 ≡ 1 (mod 7),
46 ≡ 1 (mod 7)
56 ≡ 1 (mod 7) and
66 ≡ 1 (mod 7)
How do we check whether a number is Prime or not?

(2) Fermat’s Little Theorem:

If n is a prime number, then for every a, 1 <= a < n,


an-1 ≡ 1 (mod n)
OR
an-1 % n = 1

(a) If a given number is prime, then this method always returns true

(b) If given number is composite (or non-prime), then it may return true or false (but the
probability of producing incorrect result for composite is low and can be reduced by doing more
iterations)
How do we check whether a number is Prime or not?

(2) Fermat’s Little Theorem:

// Higher value of k indicates probability of correct results for composite inputs


become higher. For prime inputs, result is always correct
Limitations of Fermat’s Little theorem:

Step 1 Repeat following k times:  Applies only to prime moduli


a) Pick a randomly in the range [2, n - 2]  Fails for composite numbers
b) If an-1 ≢ 1 (mod n), then return false
 Base a should be co-prime to p
Step 2 Return true [probably prime].
 Generates False positives

 Probabilistic, not deterministic

 Not suitable for cryptograhy


PROBLEM (3)

a) Check if Fermat’s little theorem holds for the following values p = 5 a = 2

b) Prove Fermat’s little theorem holds for p=13, a=11

c) Prove that Fermat’s little theorem does not hold for p=6 , a=2
PROBLEM (4) Count the number of ideal arrays (Fermat’s Little Theorem)
You are given two integers n and maxValue, which are used to describe an ideal array. A 0-
indexed integer array arr of length n is considered ideal if the following conditions hold:

• Every arr[i] is a value from 1 to maxValue, for 0 <= i < n.


• Every arr[i] is divisible by arr[i - 1], for 0 < i < n.

Return the number of distinct ideal arrays of length n. Since the answer may be very large,
return it modulo 109 + 7.

Example 1:
Input: n = 2, maxValue = 5
Output: 10
Explanation: The following are the possible ideal arrays:
- Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5]
- Arrays starting with the value 2 (2 arrays): [2,2], [2,4]
- Arrays starting with the value 3 (1 array): [3,3]
- Arrays starting with the value 4 (1 array): [4,4]
- Arrays starting with the value 5 (1 array): [5,5]
There are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.
PROBLEM (4) Count the number of ideal arrays (contd....)
Test Case 1:

n = 2 maxValue = 5

Expected =10
Output = 10.

Test Case 2:

n = 5 maxValue =3

Expected = 11
Output = 11
How do we check whether a number is Prime or not?

Problem (4) Sieve of Eratosthenes:

The sieve of Eratosthenes is one of the most efficient ways to find


all primes smaller than n when n is smaller than 10 million or so

Time complexity : O(nloglogn)


How do we check whether a number is Prime or not?
(4) Sieve of Eratosthenes:

1. Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n)

2. Initially, let p equal 2, the first prime number.

3. Starting from p, count up in increments of p and mark each of these


numbers greater than p itself in the list. (some of them may have already
been marked)

4. Find the first number greater than p in the list that is not marked. If there
was no such number, stop. Otherwise, let p now equal this number (which
is the next prime), and repeat from step 3.
e.g. when n = 50,

Step 1: print all numbers smaller than or equal to 50.

Step 2: Initialize p = 2

Step 3: Mark all the numbers which are divisible by p


Step 4: Find the first number greater than p in the list that is not marked.
p=3, repeat Step 3
Now, p=5,

Continue this process and our final table will look like as below,
void sieveOfEratosthenes(int n){

boolean prime[] = new boolean[n+1];

for(int i=0;i<n;i++)
prime[i] = true; LIMITATIONS:

 If n is large, the array of size Θ(n) may


for(int p = 2; p*p <=n; p++){
not fit in memory
if(prime[p] == true){
for(int i = p*2; i <= n; i += p)  The simple Sieve is not cache friendly
prime[i] = false; even for slightly bigger n. The
algorithm traverses the entire array
} without locality of reference
}
for(int i = 2; i <= n; i++){
if(prime[i] == true)
[Link](i + " ");
}
}
SieveOfEratosthenes: (Problem 2) Four Divisors

Given an integer array nums, return the sum of divisors of the integers in that array
that have exactly four divisors. If there is no such integer in the array, return 0.

Example 1:

Input: nums = [21,4,7]


Output: 32
Explanation:

21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answer is the sum of divisors of 21 only.
SieveOfEratosthenes: (Problem 2) Four Divisors (contd...)

Test Case 1:

Input:nums = [21,21]

Output:64

Expected:64

Test Case 2:

Input:nums =[1,2,3,4,5]

Output:0

Expected:0
SieveOfEratosthenes: (Problem 3) Bazinga

Sheldon is very proud of his intelligence. To test his intelligence Howard designs a puzzle and asks him to solve it.
The puzzle consists of special numbers which can be obtained by multiplying exactly two distinct prime numbers.
Sheldon has to tell Howard what is the Kth element of this series. Help him.

For example 6, 10, 14, 15 are the first few members of this series whereas 4, 9 and 12 are not.

Input
First line specifies T, the number of test cases.

Next T lines each gives 1 number, K.

Output
Output 1 line for each test case giving the Kth element of this series.

Constraints
1 ≤ T ≤ 1000

1 ≤ K ≤ 2000000
SieveOfEratosthenes: (Problem 3) Bazinga (contd...)

Example
Input:
4
2
3
5
7

Output:
10
14
21
26
How do we check whether a number is Prime or not?

Problem (5) Segmented Sieve: Limitations:

 More Complex Implementation

Divide the range [0..n-1] in different segments  Pre-sieving Still Requires √N Memory

 Cache Efficiency Can Vary


Size of each segment is √n
 Slower for Small N

Compute primes in all segments one by one  Parallelization Isn’t Straightforward


Segmented Sieve
The idea of segmented sieve is to divide the range [0..n-1] in different segments and
compute primes in all segments one by one. This algorithm first uses Simple Sieve to
find primes smaller than or equal to √(n). Below are steps used in Segmented Sieve.

1. Use Simple Sieve to find all primes upto square root of ‘n’ and store these primes in
an array “prime[]”. Store the found primes in an array ‘prime[]’.
2. We need all primes in range [0..n-1]. We divide this range in different segments such
that size of every segment is at-most √n
3. Do following for every segment [low..high]
• Create an array mark[high-low+1]. Here we need only O(x) space where x is
number of elements in given range.
• Iterate through all primes found in step 1. For every prime, mark its multiples in
given range [low..high].
In Simple Sieve, we needed O(n) space which may not be feasible for large n. Here we
need O(√n) space and we process smaller ranges at a time (locality of reference)
Find all prime factors of a given number

 Every natural number greater than 1 is either a prime itself or can be


factorized as a product of primes that is unique up to their order. E.g. 315,
can be written as 3 *3 * 5* 7

 Writing a number as a product of prime numbers is called a prime


factorization of the number. e.g. 3, 3, 5, 7 are prime factors of 315
Find all prime factors of a given number

1) While n is divisible by 2, print 2 and divide n by 2.

2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n.
While i divides n, print i and divide n by i, increment i by 2 and continue.

3) If n is a prime number and is greater than 2, then n will not become 1 by


above two steps. So print n if it is greater than 2.
Find all prime factors of a given number

1) While n is divisible by 2, print 2 and divide n by 2.

while (n%2==0)
{
[Link](2 + " ");
n /= 2;
}
Find all prime factors of a given number

2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n.
While i divides n, print i and divide n by i, increment i by 2 and continue.

for (int i = 3; i <= [Link](n); i+= 2)


{
while (n%i == 0)
{
[Link](i + " ");
n /= i;
}
}
Find all prime factors of a given number

3) If n is a prime number and is greater than 2, then n will not become 1 by


above two steps. So print n if it is greater than 2.

if (n > 2)
[Link](n);
Find all prime factors of a given number

1) While n is divisible by 2, print 2 and divide n by 2.

2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n.
While i divides n, print i and divide n by i, increment i by 2 and continue.

3) If n is a prime number and is greater than 2, then n will not become 1 by


above two steps. So print n if it is greater than 2.
Least prime factor of numbers till n

 The least prime factor of an integer n is the smallest prime number that
divides the number

 A prime number is its own least prime factor (as well as its own greatest
prime factor)

 The least prime factor of all even numbers is 2

Input : 6
Output : Least Prime factor of 1: 1
Least Prime factor of 2: 2
Least Prime factor of 3: 3
Least Prime factor of 4: 2
Least Prime factor of 5: 5
Least Prime factor of 6: 2
Least prime factor of numbers till n

1. Create a list of consecutive integers from 2 through n: (2, 3, 4, …, n).

2. Initially, let i equal 2, the smallest prime number.

3. Generate the multiples of i by counting from 2*i to n, and mark them as


having least prime factor as i (if not already marked). Also mark i as least prime
factor of i (i itself is a prime number).

4. Find the first number greater than i in the list that is not marked. If there was
no such number, stop. Otherwise, let i now equal this new number (which is
the next prime), and repeat from step 3
Least prime factor of numbers till n

int[] least_prime = new int[n+1];

//least_prime[1] = 1;

for (int i = 2; i <= n; i++){


if (least_prime[i] == 0){
least_prime[i] = i;
for (int j = 2*i; j <= n; j += i)
if (least_prime[j] == 0)
least_prime[j] = i;
}
} Time Complexity: O(nlog(n))
Auxiliary Space: O(n)
Segmented Sieve: (Problem 2) BSPRIME

Binary Sequence of Prime Number is a binary sequence that created by converting prime number to base-2
(without leading zeros):
(2)10=(10)2
(3)10=(11)2
(5)10=(101)2
(7)10=(111)2
If all base-2 of prime number joined, then we get the binary sequence like this: 10111011111011110110

Now your task is to count how many digit '1' appear in the first N terms of the sequence, example:

If N=3, digit '1' appear 2 times: 101110...


If N=10, digit '1' appear 8 times: 1011101111101

Input
The first line is an integer T (1 ≤ T ≤ 50,000), denoting the number of test cases. Then, T test cases follow.

For each test case, there is an integer N (0 ≤ N ≤ 150,000,000) written in one line.

Output
Segmented Sieve: (Problem 2) BSPRIME (contd...)

Example
Input:
3
3
10
50

Output:
2
8
36
Segmented Sieve: (Problem 3) PRINT - Prime Intervals

In this problem you have to print all primes from given interval.

Input
t - the number of test cases, then t lines follows. [t <= 150]
On each line are written two integers L and U separated by a blank.
L - lower bound of interval
U - upper bound of interval.
[2 <= L < U <= 2147483647]
[U-L <= 1000000].

Output
For each test case output must contain all primes from interval [L; U] in increasing order.
Segmented Sieve: (Problem 3) PRINT - Prime Intervals (contd...)

Example
Input:

2
2 10
37

Output:

2
3
5
7
3
5
7
Problem 6-Prime Factorization using Sieve O(log n)

1. Use PrimeFactors[] to store result

2. i = 0

3. while n != 1 :
PrimeFactors[i] = LPF[n] (LPF is Least Prime Factor)
i++
Limitations of LPF based Prime Factorization:
n = n / LPF[n]
 Need to precompute the LPF[] array using sieve
 Requires O(n) space to store the LPF[] array
 Can’t factorize numbers larger than the precomputed range
 Not cache efficient
 Not useful for single query
 Not suitable for cryptography
Prime Factorization using Sieve O(log n) for multiple queries

1. Use PrimeFactors[] to store result

2. i = 0

3. while n != 1 :
PrimeFactors[i] = LPF[n] (LPF is Least Prime Factor)
i++
n = n / LPF[n]
Problem 7-Twin Prime (prime number that is either 2 less or 2 more than another
prime number, e.g (17,19),(41,43))

Limitations:
(a) Check whether two numbers are twin primes or not?
 The twin primes checking is
naive
 Extra Space Complexity of
(b) Find the twin prime pair closest to 10. O(n)
 Inefficient for large values of
n
(c) What is the next twin prime pair after (5,7)?

(d) Identify the twin prime pair between 50 and 60.


Problem 8-Twisted Prime
Given a number N. Check whether N is a Twisted Prime number or not.(Twisted
prime number whose reverse is also a prime number. e.g (13,31), (79,97) )
Example 1:

Limitations:
Input: N = 97
 Inefficient for Large Numbers
Output: 1  Repeated primality checks
Explanation: 97 is a prime number. Its without caching or sieving
 Doesn't handle negative inputs or
reverse 79 isalso a prime number. Thus
0 gracefully
97 is a twisted Prime and so, answer is 1.  Generation of invalid primes

Expected Time Complexity:(O(sqrt(max(N,RevN))), here RevN is the reverse of N.


Expected Space Complexity:O(1)

Constraints:
1<=N<=109
Problem 9-Sieve Of Atkin

The sieve of Atkin is a modern algorithm for finding all prime numbers up to a
specified integer. Compared with the ancient Sieve of Eratosthenes , which marks
off multiples of primes, it does some preliminary work and then marks off
multiples of squares of primes, that’s why it has a better theoretical asymptotic
complexity with Complexity of (N / (log log N))

Limitations:
 Much harder to implement correctly than Sieve of Eratosthenes.
 Only marginally better than Eratosthenes for extremely large n, and only in
optimized implementations.
 Not Well-Suited for Small n
[Link] a results list, filled with 2, 3, and 5.
[Link] a sieve list with an entry for each positive integer; all entries of this list should
initially be marked non prime.
[Link] each entry number n in the sieve list, with modulo-sixty remainder r:
1. If r is 1, 13, 17, 29, 37, 41, 49, or 53, flip the entry for each possible solution to
4x2 + y2 = n.
2. If r is 7, 19, 31, or 43, flip the entry for each possible solution to 3x 2 + y2 = n.
3. If r is 11, 23, 47, or 59, flip the entry for each possible solution to 3x 2 – y2 = n when
x > y.
4. If r is something else, ignore it completely..
[Link] with the lowest number in the sieve list.
[Link] the next number in the sieve list still marked prime.
[Link] the number in the results list.
[Link] the number and mark all multiples of that square as non prime. Note that the
multiples that can be factored by 2, 3, or 5 need not be marked, as these will be ignored in
the final enumeration of primes.
[Link] steps four through seven
How it Works:
1. The algorithm treats 2, 3 and 5 as special cases and just adds them to the set of primes to start
with.
2. Like Sieve of Eratosthenes, we start with a list of numbers we want to investigate. Suppose we
want to find primes <=100, then we make a list for [5, 100]. As explained in (1), 2, 3 and 5 are special
cases and 4 is not a prime.
3. The algorithm talks in terms of modulo-60 remainders. .
4. All numbers with modulo-sixty remainder 1, 13, 17, 29, 37, 41, 49, or 53 have a modulo-twelve
remainder of 1 or 5. These numbers are prime if and only if the number of solutions to 4×2+y2=n is
odd and the number is squarefree. A square free integer is one which is not divisible by any perfect
square other than 1.
5. All numbers with modulo-sixty remainder 7, 19, 31, or 43 have a modulo-six remainder of 1.
These numbers are prime if and only if the number of solutions to 3x2 + y2 = n is odd and the
number is squarefree.
6. All numbers with modulo-sixty remainder 11, 23, 47, or 59 have a modulo-twelve remainder of
11. These numbers are prime if and only if the number of solutions to 3x2 – y2 = n is odd and the
number is squarefree.
// C++ program for implementation of Sieve of Atkin b) n = (3*x*x)+(y*y) has odd number of // Mark all multiples of squares as non-prime
#include <bits/stdc++.h> solutions and n % 12 = 7 for (int r = 5; r * r < limit; r++) {
using namespace std; c) n = (3*x*x)-(y*y) has odd number of if (sieve[r]) {
solutions, x > y and n % 12 = 11 */ for (int i = r * r; i < limit; i += r * r)
int SieveOfAtkin(int limit) for (int x = 1; x * x < limit; x++) { sieve[i] = false;
{ for (int y = 1; y * y < limit; y++) { }
// 2 and 3 are known to be prime }
if (limit > 2) // Main part of Sieve of Atkin
cout << 2 << " "; int n = (4 * x * x) + (y * y); // Print primes using sieve[]
if (limit > 3) if (n <= limit && (n % 12 == 1 || n % 12 == 5)) for (int a = 5; a < limit; a++)
cout << 3 << " "; sieve[n] ^= true; if (sieve[a])
cout << a << " ";
// Initialise the sieve array with false values n = (3 * x * x) + (y * y); }
bool sieve[limit]; if (n <= limit && n % 12 == 7)
for (int i = 0; i < limit; i++) sieve[n] ^= true; // Driver program
sieve[i] = false; int main(void)
n = (3 * x * x) - (y * y); {
/* Mark siev[n] is true if one if (x > y && n <= limit && n % 12 == 11) int limit = 20;
of the following is true: sieve[n] ^= true; SieveOfAtkin(limit);
a) n = (4*x*x)+(y*y) has odd number of } return 0;
solutions, i.e., there exist } }
odd number of distinct pairs (x, y)
that satisfy the equation and
n % 12 = 1 or n % 12 = 5.
Problem 10 -(Sieve Of Atkin) Prime Subtraction Operation

You are given a 0-indexed integer array nums of length n.

You can perform the following operation as many times as you want:

• Pick an index i that you haven’t picked before, and pick a prime p strictly less than
nums[i], then subtract p from nums[i].

Return true if you can make nums a strictly increasing array using the above operation and
false otherwise.

A strictly increasing array is an array whose each element is strictly greater than its
preceding element.
Problem 10 -(Sieve Of Atkin) Prime Subtraction Operation (contd...)

Example 1:

Input: nums = [4,9,6,10]


Output: true
Explanation: In the first operation: Pick i = 0 and p = 3, and then subtract 3 from nums[0], so
that nums becomes [1,9,6,10].
In the second operation: i = 1, p = 7, subtract 7 from nums[1], so nums becomes equal to
[1,2,6,10].
After the second operation, nums is sorted in strictly increasing order, so the answer is true.

Constraints:

1 <= [Link] <= 1000


1 <= nums[i] <= 1000
[Link] == n
Problem 10 -(Sieve Of Atkin) Prime Subtraction Operation (contd...)

Test Case 1:

Input: nums = [6,8,11,12]

Output: true

Test Case 2:

Input: nums = [5,8,3]

Output: false
Patterns involving Prime Numbers

Prime Number Series


Consists of prime numbers (divisible only by 1 and themselves).

Example:
2, 3, 5, 7, 11, 13, 17, ...
Patterns involving Prime Numbers
Prime series can be modified to create interesting sequences:

• Shifted primes: Sequence obtained by adding or subtracting a constant to


prime numbers: e.g. Adding k =1 to prime number series, when n = 3

pn + k -> 2+1, 3+1, 5+1 -> 3,4,6

• Scaled Primes: Multiplying a constant factor to prime numbers: e,g


c x pn -> 2pn -> , gives every numbers except 2.

• Indexed formulas: f(n,pn) where pn is the n-th prime.


an = n x (pn + 1)
Patterns involving Prime Numbers

• Many sequences hides primes in a transformed way.

• Primes are not evenly spaced.

• Primes can be used to find nth term of a series


Problem 11 :Mansi and her series
Mansi is fond of solving mental ability questions. Today while solving some
questions she came across a series which she was unable to solve. Help her to find
the nth term of the series.
n nth term
1 3
2 8
3 18
4 32
5 60
.
.
.
10 300
Problem 11 :Mansi and her series (contd...)
Example 1:

Input: n = 1
Output: 3
Explanation: The first term of the series is 3.

Example 2:

Input: n = 2
Output: 8
Explanation: The second term of the series is 3.

Expected Time Complexity: O(nlogn)


Expected Auxiliary Space: O(n)

Constraints:
Problem 12 :Collections of Pens
There are three piles of pens. A pens in the first pile and B pens in the second [Link] the minimum number of pens that should be there in
the third pile so that sum of all three piles produces either a prime number or unity.
Note: there should be atleast one pen in the third pile.

Example 1:

Input: A = 1, B = 3
Output: 1
Explanation: A + B + K = prime
K = 1, 1 + 3 + 1 = [Link] answer = 1
becuase 5 is minimum possible prime.

Example 2:

Input: A = 4, B = 3
Output: 4
Explanation: A + B + K = prime
K = 4, 4 + 3 + 4 = [Link] answer = 4
Problem 12 :Collections of Pens (contd...)

Expected Time Complexity: O(nlogn)


Expected Auxiliary Space: O(1)

Constraints:
1 <= A <=1000
1 <= B <=1000
Problem 13 : Next Prime Palindrome
You will be given a positive integer N. Your task is to find the smallest number greater than or equal to N that is a
prime and a palindrome.

Example 1:
Input: N = 12
Output: 101

Example 2:
Input: N = 4
Output: 5

Expected Time Complexity: O(N)


Expected Space Complexity: O(1)

Constraints:
1 <= N <= 106
Problems to solve

6. Check if a number is Full Prime

7. Insert minimum number in array so that sum of array becomes prime

8. Find the prime numbers which can written as sum of most consecutive
primes

9. Find two prime numbers with given sum

10. Twisted Prime Number

11. Almost Prime Numbers


Problems to solve

12. Check if a number can be written as a sum of ‘k’ prime numbers

13. Special prime numbers

14. Twin Prime Numbers between 1 and n

15. K-Primes (Numbers with k prime factors) in a range

You might also like