using
System;
public
class
Node
{
public
int
data;
public
Node next;
public
Node(
int
num)
{
data = num;
next =
null
;
}
}
public
class
MainClass
{
static
bool
[] Sieve(
int
n)
{
bool
[] isPrime =
new
bool
[n + 1];
for
(
int
i = 0; i <= n; i++)
{
isPrime[i] =
true
;
}
isPrime[0] = isPrime[1] =
false
;
for
(
int
p = 2; p * p <= n; p++)
{
if
(isPrime[p])
{
for
(
int
i = p * p; i <= n; i += p)
{
isPrime[i] =
false
;
}
}
}
return
isPrime;
}
static
int
NearestPrime(
int
num,
bool
[] isPrime)
{
if
(num >= 0 && num < isPrime.Length && isPrime[num])
return
num;
if
(num <= 1)
return
2;
int
lower = num - 1;
int
upper = num + 1;
while
(
true
)
{
if
(lower >= 0 && lower < isPrime.Length && isPrime[lower])
return
lower;
if
(upper < isPrime.Length && isPrime[upper])
return
upper;
lower--;
upper++;
}
}
static
void
InsertPrime(Node head,
bool
[] isPrime)
{
Node p1 = head;
Node p2 = head.next;
while
(p2 !=
null
)
{
int
sum = p1.data + p2.data;
int
p = NearestPrime(sum, isPrime);
Node temp =
new
Node(p);
p1.next = temp;
temp.next = p2;
p1 = temp.next;
p2 = p2.next;
}
}
static
void
PrintList(Node head)
{
Node current = head;
while
(current.next !=
null
)
{
Console.Write(current.data +
" -> "
);
current = current.next;
}
Console.WriteLine(current.data);
}
public
static
void
Main()
{
int
maxNum = 100;
bool
[] isPrime = Sieve(maxNum);
Node head =
new
Node(2);
head.next =
new
Node(4);
head.next.next =
new
Node(7);
head.next.next.next =
new
Node(5);
head.next.next.next.next =
new
Node(9);
Console.Write(
"Given Linked List: "
);
PrintList(head);
Console.WriteLine();
InsertPrime(head, isPrime);
Console.Write(
"Resultant Linked List: "
);
PrintList(head);
}
}