In: Computer Science
answer the following using C#
Design and program a Visual Studio Console project in C# that allows your user to enter a number. The program will examine the number to see if it is prime. If it is prime, it will print the next higher prime and the next lower primes to the console. If the number entered by the user is not prime, display a message to that effect.
All code should be written by you. Do not copy/paste any code from any other source.
Assume the input will be within the range 2 to (2^31-1)
You should not validate the user input.
using System;
using System.Dynamic;
namespace prime
{
class Program
{
static void Main(string[] args)
{
//Declaring variables flag is for finding prime in first loop
//flag is for finding lower prime
//flag is for finding higher prime
int value, flag = 0, flag1 = 0, flag2 = 0;
Console.WriteLine("Enter value: ");
//Reading value from user
value = int.Parse(Console.ReadLine());
//Asking the user to enter value greater than zero
if (value <= 0)
Console.WriteLine("Enter value greater than zero");
else
{
//To check whether given value is prime or not
for (int i = 2; i < value; i++)
{
//If any of the value which is less than user value modulous equal
to zero then break
if (value % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
{
//Finding lower prime value
for(int j = value-1; j >= 1; j--)
{
int prime = 0;
for(int k=2; k < j; k++)
{
if (j % k == 0)
{
prime = 1;
break;
}
}
//This condition to check no lower value is presenty
if (prime == 0)
{
flag1 = 1;
Console.WriteLine($"The next lower prime is {j}");
break;
}
}
if (flag1 == 0)
{
Console.WriteLine("There is no lower prime for the given
value");
}
//Finding higher prime value
for(int j=value+1;Math.Abs(j)<= 2147483647;
j++)
{
int prime = 0;
for (int k = 2; k < j; k++)
{
if (j % k == 0)
{
prime = 1;
break;
}
}
if (prime == 0)
{
flag2 = 1;
Console.WriteLine($"The next higher prime is {j}");
break;
}
}
if (flag2 == 0)
{
Console.WriteLine("There is no higher prime for the given
value");
}
}
else
Console.WriteLine("The given vaue is not a prime");
}
}
}
}
Sample Input and output:
Enter value:
2147483647
The next lower prime is 2147483629
The next higher prime is -2147483648
//If you observe the above condition for the highest value which is 2^31 - 1 has lower prime and higher prime is negative value. This is because range of int from -2147483648 to 2147483647. To avoid these situation I added Math.abs value to above code which is in bold.
Enter value:
2147483647
The next lower prime is 2147483629
//If you apply Math.Abs then below exception will be raised.
//System.OverflowException: 'Negating the minimum value of a twos complement number is invalid.'
Enter value:
37
The next lower prime is 31
The next higher prime is 41
Enter value:
7
The next lower prime is 5
The next higher prime is 11