Exercise
Function Isprimetarea
Objective
Write a C# function named "IsPrime", which receives an integer number and retuns true if it is prime, or false if it is not:
if (isPrime(127)) ...
Write Your C# Exercise
C# Exercise Example
// Importing the System namespace to access basic system functions
using System;
class Program
{
// Function to check if a number is prime
public static bool IsPrime(int number)
{
// A prime number is greater than 1 and has no divisors other than 1 and itself
if (number <= 1)
{
return false; // Numbers less than or equal to 1 are not prime
}
// Loop through numbers from 2 to the square root of the number
for (int i = 2; i * i <= number; i++)
{
// If the number is divisible by any number in the range, it is not prime
if (number % i == 0)
{
return false; // Not a prime number
}
}
// If no divisors are found, the number is prime
return true;
}
// Main method where the IsPrime function is called
public static void Main()
{
// Test the function with the number 127
if (IsPrime(127))
{
Console.WriteLine("127 is a prime number.");
}
else
{
Console.WriteLine("127 is not a prime number.");
}
}
}