Skip to content

Commit 19e5905

Browse files
Merge pull request #227 from Mukulbaid63/pf_3
N digit prime added
2 parents a062570 + 096a037 commit 19e5905

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

Diff for: Java/NthDigitMaxPrime/MaxPrime.java

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
imjort java.util.*;
2+
3+
class MaxPrime
4+
{
5+
static int limit = 100000000;
6+
static boolean[] sieve = new boolean[limit + 1];
7+
8+
/*The Sieve of Eratosthenes marks all the no.s except
9+
primes to false in the bool arr in most optimal way.*/
10+
static void SieveOfEratosthenes()
11+
{
12+
for (int i=0;i<limit+1;i++)
13+
{ //setting all values to true
14+
sieve[i]=true;
15+
}
16+
for (int j=2;j*j<=limit;j++)
17+
{
18+
if(sieve[j]==true)
19+
{ //setting all the multiples of j as false
20+
for (int i=j*j;i<=limit;i+=j)
21+
sieve[i]=false;
22+
}
23+
}
24+
}
25+
26+
static int maxPrime(int d)
27+
{
28+
int l=(int)Math.pow(10,d-1); //lowest d digit number
29+
int r=(int)Math.pow(10,d)-1; //highest d digit number
30+
for (int i=r;i>=l;i--)
31+
{ /**The first index with true value in sieve[] will be
32+
the answer as we are traversing in decreasing order */
33+
if(sieve[i])
34+
{
35+
return i;
36+
}
37+
}
38+
39+
return -1;
40+
}
41+
42+
43+
public static void main(String[] args)
44+
{
45+
SieveOfEratosthenes();
46+
47+
Scanner sc=new Scanner(System.in);
48+
int n=sc.nextInt();//Input
49+
50+
System.out.println(maxPrime(n)); //Output
51+
52+
}
53+
}
54+

Diff for: Java/NthDigitMaxPrime/README.md

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Sample Input:
2+
3+
2
4+
5+
6+
7+
# Sample Output:
8+
9+
97
10+
11+
12+
13+
# Sample Input:
14+
15+
6
16+
17+
18+
19+
# Sample Output:
20+
21+
999983
22+
23+
24+
25+
# Explaination:
26+
TC 1:
27+
l=10^(2-1)=10
28+
r=10^2-1=99
29+
30+
After checking in the sieve[] in decreasing order,the first time comes out to be 97
31+
32+
33+
# Time Complexity:
34+
35+
<h3>O(limit log(log limit))</h3>,where limit is the size of the sieve[].This is the most optimal way to find out the required solution.

0 commit comments

Comments
 (0)