Answered step by step
Verified Expert Solution
Link Copied!

Question

00
1 Approved Answer

With Ruby write a program that asks the user to enter a number and then prints out whether or not that number is prime. If

With Ruby write a program that asks the user to enter a number and then prints out whether or not that number is prime. If it is not prime, the program must print out each divisor of the number.

A number is prime if it is divisible only by itself and 1. For example, 7 is a prime number because no other numbers besides 7 and 1 evenly divide 7. 6 is not a prime number because its divisors are 1, 2, 3, and 6. There are many ways to determine if a number, n, is prime or not. The simplest way is to start with 1 and count up to n while keeping track of which numbers evenly divide n: is Prime?(n) factors = empty array for i = 2 to n-1 if i evenly divides n add i to factors if factors array is empty return false else return factors In this assignment, you are to prompt the user to enter a number, and then determine if the number is prime or not. If the number is not prime, then you are to print out the number along with its factors, otherwise print out an indication that the number is prime. We can tell if one number evenly divides another number by examining the remainder. Recall that the way to do this in Ruby is through the use of the modulus operator. If x evenly divides y, then x % y evaluates to 0; if x does not evenly divide y, then x % y will be some positive number.

The program should run like this:

Enter a number: 7

7 is a prime number

Enter a number: 6

6 is not a prime number => 2, 3

Enter a number: 144

144 is not a prime number => 2, 3, 4, 6, 8, 9, 12, 16, 18, 24, 36, 48, 72

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions

Question

Exchanges of assets for assets, have what effect on equity

Answered: 1 week ago