Rust program to check a given number is prime or not using recursion

Rust | Checking Prime Number Example: Given a number, we have to check whether it’s a prime number or not using recursion.
Submitted by Nidhi, on October 11, 2021

Problem Solution:

In this program, we will create a recursive function to check a given number is prime or not using recursion.

Program/Source Code:

The source code to check a given number is prime or not using recursion is given below. The given program is compiled and executed successfully.

// Rust program to check a given number 
// is prime or not using recursion

fn checkPrime(num:i32, i:i32)->i32{
    if (i == 1){
        return 1;
    }
    else{
       if (num % i == 0)
       {
         return 0;
       }
       else
       {
         return checkPrime(num, i - 1);
       }       
    }
}

fn main() {
    let num:i32=11;
    let rs = checkPrime(num,num/2);
    
    if rs == 1
    {
        println!("{} is a prime number.", num);
    }
    else
    {
        println!("{} is not a prime number.", num);
    }
}

Output:

11 is a prime number.

Explanation:

In the above program, we created two functions checkPrime() and main(). The checkPrime() function is a recursive function, which is used to check a given number is prime or not and return the result to the calling function.

In the main() function, we called the checkPrime() function and printed the result.

Rust Functions Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.