Q:

Ruby program to find the given number is PRIME or not using recursion

belongs to collection: Ruby User-defined Functions Programs

0

In this program, we will read an integer number from the user and find the input 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 find the given number is PRIME or not using recursion is given below. The given program is compiled and executed successfully.

# Ruby program to find the given number 
# is PRIME or not using recursion

def checkPrime(num, i)
    if (i == 1)
        return 1;
    else
       if (num % i == 0)
         return 0;
       else
         return checkPrime(num, i - 1);
       end    
    end
end

print "Enter number: ";
number = gets.chomp.to_i;  

result = checkPrime(number, number/2);

if result==1
    print "Given number is PRIME number.";
else
    print "Given number is not PRIME number.";
end

Output:

Enter number: 11
Given number is PRIME number.

Explanation:

In the above program, we read an integer number from the user. Then we found the input number is PRIME or not using recursive function checkPrime(). Then we printed the result.

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

total answers (1)

Ruby User-defined Functions Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Ruby program to find the LCM of two given numbers ... >>
<< Ruby program to find the reverse of a given number...