Q:

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

belongs to collection: Rust Functions Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Rust program to calculate the LCM using recursion... >>
<< Rust program to reverse a number using recursion...