# Solved: PRIME NUMBER

Prime numbers hold a significant place in the field of mathematics and computing. Essentially, a prime number is a natural number greater than one and has no positive divisors other than one and itself. For instance, the first six prime numbers are 2, 3, 5, 7, 11, and 13. Understanding and working with prime numbers is crucial in several areas, such as encryption algorithms and factoring, among others.

## The Solution to the Prime Number Problem

The key issue with prime numbers in programming or computational mathematics is determining whether a given number is prime or not. To be precise, our objective here is to test if ‘n’ (a non-negative integer) is a prime number. To resolve this problem, we will implement a simple algorithm.

Our approach will include checking if ‘n’ is not a multiple of any integer between 2 and square root of ‘n.’ If it isn’t, we conclude that ‘n’ is a prime number. This is based on the mathematical fact that a larger factor of the number is always a multiple of a smaller factor that has already been checked.

## Cobol Code to Determine Prime Numbers

This segment includes the code needed to resolve the prime number problem in Cobol. Here’s how to do it:

IDENTIFICATION DIVISION.
PROGRAM-ID. Main.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num PIC 99.
01 x PIC 99.
PROCEDURE DIVISION.
START.
DISPLAY “Enter a number : “.
ACCEPT Num.
PERFORM VARYING x FROM 2 BY 1 UNTIL x * x > Num
IF Num MOD x = 0
DISPLAY Num ” is not a prime number.”
EXIT PROGRAM
END-IF
END-PERFORM.
DISPLAY Num ” is a prime number.”
STOP RUN.

## Understand the Code

Following are the steps of the prime number solution:

• We begin by defining two variables, ‘Num’ and ‘x’.
• We solicit a number from the user and store it in ‘Num’.
• Next, using a PERFORM loop, we begin dividing ‘Num’ from 2 incrementally. We continue this until ‘x’ squared is larger than ‘Num’.
• Inside the loop, if ‘Num’ can be evenly divided by ‘x’ (i.e. remainder =0), ‘Num’ is not a prime number and we terminate the program.
• If we exit the loop without finding such an ‘x’, then ‘Num’ is a prime number.

## Libraries and Functions Involved

This simple Cobol program does not require any additional libraries or functions. There’s the use of basic Cobol language syntax, and we’re leveraging some built-in operations like ACCEPT (to get user input), DISPLAY (to print to the console), and PERFORM (to loop through potential divisors). The MOD function allows us to find the remainder of division, which is key to solving the prime number problem.

Whether you’re creating secure keys for encryption or need prime numbers for other computational tasks, understanding and being able to determine prime numbers is a valuable skill in your programming arsenal. Familiarize yourself with this Cobol script to recognize and utilize prime numbers effectively.

Related posts: