w3resource

C# Sharp Exercises: Next prime number of a given integer

C# Sharp Basic: Exercise-92 with Solution

Write a C# Sharp program to find the next prime number of a given number. If the given number is a prime number, return the number.

From Wikipedia,
A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number. For example, 5 is prime because the only ways of writing it as a product, 1 × 5 or 5 × 1, involve 5 itself. However, 4 is composite because it is a product (2 × 2) in which both numbers are smaller than 4. Primes are central in number theory because of the fundamental theorem of arithmetic: 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.

Sample Solution:

C# Sharp Code:

using System;
using System.Linq;
namespace exercises
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 120;
            Console.WriteLine("Original number: " + n);
            Console.WriteLine("Next prime number/Current prime number: " + test(n));
            n = 321;
            Console.WriteLine("\nOriginal number: " + n);
            Console.WriteLine("Next prime number/Current prime number: " + test(n));
            n = 43;
            Console.WriteLine("\nOriginal number: " + n);
            Console.WriteLine("Next prime number/Current prime number: " + test(n));
            n = 4433;
            Console.WriteLine("\nOriginal number: " + n);
            Console.WriteLine("Next prime number/Current prime number: " + test(n)); ;
        }
        public static int test(int n)
        {
            for (int i = 2; i < n; i++)
            {
                if (n % i == 0) { n++; i = 2; }
            }
            return n;
        }
    }
}

Sample Output:

Original number: 120
Next prime number/Current prime number: 127

Original number: 321
Next prime number/Current prime number: 331

Original number: 43
Next prime number/Current prime number: 43

Original number: 4433
Next prime number/Current prime number: 4441

Flowchart:

Flowchart: C# Sharp Exercises - Next prime number of a given integer.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous C# Sharp Exercise: Write a C# Sharp program to remove all the values except integer values from a given array of mixed values.
Next C# Sharp Exercise: Square root of a given number.

What is the difficulty level of this exercise?



Share this Tutorial / Exercise on : Facebook and Twitter