ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.