From the course: Advanced C#: Functional Programming Patterns

Unlock this course with a free trial

Join today to access over 24,500 courses taught by industry experts.

IsPrime function as an expression

IsPrime function as an expression - C# Tutorial

From the course: Advanced C#: Functional Programming Patterns

IsPrime function as an expression

For the last example, I chose the classic IsPrime number function. We'll see how to create the function with expressions and how to call it with expressions. So here's the actual function that calculates whether it's a prime. It returns a Boolean, it's called IsPrime, and it takes an integer value. And then I'm calling that here in this other expression. We'll talk about this section in a minute. So what's happening here. Well, we start off with this part of the expression which is checked whether the number is greater than one; prime numbers must be greater than one. Then the next section is here from enumerable to the square root, -1, that generates a range of potential divisors. It generates a sequence of integers starting from two up to the integer value of the square root of the number, -1. The reason for checking up to the square root of that number is if it's divisible by any number greater than its square root, it would already be divisible by a smaller number. Step number…

Contents