c-sharp
  1. c-sharp-program-to-check-whether-a-number-can-be-expressed-as-sum-of-two-prime-numbers

Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers - (C# Basic Programs)

In this tutorial, we will discuss a C# program that checks whether a number can be expressed as a sum of two prime numbers or not. This program uses a brute-force approach to solve the problem.

Syntax

The syntax for checking whether a number can be expressed as a sum of two prime numbers in C# is as follows:

using System;

namespace PrimeNumbers {

  class Program {
    static bool IsPrime(int n) {
      // code to check if n is prime
      return true;
    }

    static void Main(string[] args) {
      int num = 10;
      bool found = false;
      for (int i = 2; i <= num / 2; i++) {
        if (IsPrime(i)) {
          if (IsPrime(num - i)) {
            Console.WriteLine("{0} can be expressed as the sum of {1} and {2}", num, i, num - i);
            found = true;
          }
        }
      }
      if (!found) {
        Console.WriteLine("{0} cannot be expressed as the sum of two prime numbers", num);
      }
    }
  }
}

Example

using System;

namespace PrimeNumbers {

  class Program {
    static bool IsPrime(int n) {
      if (n <= 1) {
        return false;
      }
      for (int i = 2; i <= n / 2; i++) {
        if (n % i == 0) {
          return false;
        }
      }
      return true;
    }

    static void Main(string[] args) {
      int num = 10;
      bool found = false;
      for (int i = 2; i <= num / 2; i++) {
        if (IsPrime(i)) {
          if (IsPrime(num - i)) {
            Console.WriteLine("{0} can be expressed as the sum of {1} and {2}", num, i, num - i);
            found = true;
          }
        }
      }
      if (!found) {
        Console.WriteLine("{0} cannot be expressed as the sum of two prime numbers", num);
      }
    }
  }
}

Output:

10 can be expressed as the sum of 3 and 7

Explanation

The program checks whether a given number can be expressed as the sum of two prime numbers or not. It uses a function called IsPrime that checks whether a number is prime or not. The program then loops through all possible pairs of prime numbers that add up to the given number. If such a pair is found, the program prints the pair; otherwise, it prints that the number cannot be expressed as the sum of two prime numbers.

Use

This C# program is useful for mathematicians or developers who want to identify all possible pairs of prime numbers that add up to a given number.

Summary

In this tutorial, we have discussed a C# program that checks whether a number can be expressed as a sum of two prime numbers or not. We have seen the syntax, an example, explanation, use, and the importance of the program. This program helps in identifying prime numbers that add up to a given number, which can be useful for a variety of mathematical applications.

Published on: