Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

what should i add to this to see when it is not prime u have to find the closest

ID: 3698182 • Letter: W

Question

what should i add to this to see when it is not prime u have to find the closest prime number (higher or a lower number) { Console.WriteLine("Enter a number"); int i = Convert.ToInt32(Console.ReadLine()); int o = 0; int x = 0; int k = 2; while (i != -1) { int w = 0; for (k = 2; k < i; k++) { if (i % k == 0) { w++; Console.WriteLine("{0} is divisible by {1}", i, k); } } if (w == 0) { o++; { Console.WriteLine("Number is prime"); } } else Console.WriteLine("Number is not prime"); Console.WriteLine("Enter a number -1 to quit"); i = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("You entered {0} primes, {1} non-primes", o, x); } } } }

Explanation / Answer

add this logic with some modifications in else case

int i1

for( i1=num;;i1++)//No end limit as when prime will be found we will break the loop.
{
if(isPrime(i1))//check prime or not according to your logic
{
diff1=i1-num;
num1=i1;
break;
}
}

int i2
for(int i2=num;;i2--)//No end limit as when prime will be found we will break the loop.
{
if(isPrime(i2))
{
diff2=num-i2;
num2=i2;
break;
}
}
if(diff1<diff2)//Nearest Prime number will have least difference from given number.

Console.WriteLine("{0} Nearest Prime Number is", num1);

else if(diff2<diff1)
  Console.WriteLine("{0} Nearest Prime Number is", num2);

else//There can be more than 1 nearest prime like for 6 we have 5 and 7 as nearest prime.
{

Console.WriteLine("{0} Nearest Prime Number is", num1);
Console.WriteLine(", ", num2);

}