Group
Functions in C#
Objective
1. Define the "IsPrime" function that receives an integer number as a parameter.
2. The function should return true if the number is prime and false otherwise.
3. Use a loop to check if the number is divisible by any number between 2 and the square root of the number (this reduces the number of checks needed).
4. In the Main method, test the "IsPrime" function with a number, for example, 127, and display the result.
Write a C# function named "IsPrime", which receives an integer number and returns true if it is prime, or false if it is not.
public static void Main()
{
// Test if 127 is a prime number and print the result
if (IsPrime(127))
{
Console.WriteLine("127 is a prime number.");
}
else
{
Console.WriteLine("127 is not a prime number.");
}
}
Example C# Exercise
Show C# Code
using System;
class Program
{
// Main method where the program execution begins
public static void Main()
{
// Test if 127 is a prime number and print the result
if (IsPrime(127))
{
Console.WriteLine("127 is a prime number.");
}
else
{
Console.WriteLine("127 is not a prime number.");
}
}
// Function to check if a number is prime
public static bool IsPrime(int num)
{
// A prime number is greater than 1
if (num <= 1)
{
return false; // Numbers less than or equal to 1 are not prime
}
// Check for divisibility from 2 to the square root of the number
for (int i = 2; i <= Math.Sqrt(num); i++)
{
// If the number is divisible by any number other than 1 and itself, it is not prime
if (num % i == 0)
{
return false; // The number is not prime
}
}
// If no divisors are found, the number is prime
return true;
}
}
Output
127 is a prime number.