Home » Ruby programming » Ruby programs

# Ruby program to check whether the given number is prime or not

**Checking prime number in Ruby**: Here, we are going to learn **how to check whether a given number is a prime number or not in Ruby programming language?**

Submitted by Hrithik Chandra Prasad, on August 07, 2019

## Checking prime number

Before getting into writing the code, let us understand **what exactly the prime numbers are?** So that we could easily design its logic and implement it in the code. Prime numbers are those numbers which can only be divisible by itself or 1. So, we will design a code which can fulfill the property of **prime numbers**.

**Methods used:**

**puts**: For giving the output as well as a message to the user.**gets**: For taking the input from the user.**.to_i**: For converting strings into integers.

**Operators used:**

**%**: For retrieving the remainder.**==**: Used for comparing two values.**<**and**>**: These are comparison operators.**+**: Generally used in the code for incrementing the loop variable.

**Variables used:**

**num**: It is storing the user inputted integer value.**count**: Initialised with 0 and used as a counter variable.

### Ruby code to check weather a number is prime or not

=begin Ruby program to check whether the given number is prime or not. =end puts "Enter the number:" num=gets.chomp.to_i count=0 if (num==0) puts "0 is not prime" else i=2 while(i<num) if (num%i==0) count+=1 end i+=1 end end if count>1 puts "#{num} is not a prime number" else puts "#{num} is a prime number" end

**Output**

RUN 1 : Enter the number: 13 13 is a prime number RUN 2: Enter the number: 890 890 is not a prime number

**Code explanation:**

This program checks whether the **integer input is prime or not**. The input is checked using the while loop and conditions. Based on the condition check the code prints the required output.

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.