In this program you need to take input from user using PARAMETERS and find whether it is Prime or not. The number which is divisible only by 1 or by itself is called Prime number while the number which is divisible by any other number also apart from 1 and itself is not a Prime number.
In the program(Prime Number Program in ABAP) given below we will find whether the number entered is Prime or not.
PARAMETERS p_num TYPE int2. DATA: lv_check TYPE int2 VALUE 2, lv_flag TYPE int1 VALUE 0, lv_length TYPE c. IF p_num EQ 1. MESSAGE '1 is neither Prime nor Composite' TYPE 'I'. ELSEIF p_num IS INITIAL. MESSAGE 'Input cannot be empty or 0' TYPE 'I'. ELSE. WHILE lv_check <= p_num / 2 . IF ( p_num MOD lv_check ) EQ 0. lv_flag = 1. EXIT. ENDIF. lv_check = lv_check + 1. ENDWHILE. IF lv_flag EQ 0. WRITE 'Prime'. ELSE. WRITE 'Not Prime : Composite'. ENDIF. ENDIF.
Line 01: Here, we define a parameter to take an input from user, the input will be always a number.
Line 02: Here we will define some fields that will be utilized in the program later. lv_check will be used to check if the number is divisible by any number which is less than or equal to its half or not, lv_flag will be used to set flag 0 or 1. Flag = 0 will mean, number is prime and 1 will mean, number is not prime. lv_length will be used to check the length of the number.
Line 03: Here we will check if the number is one or not.
Line 04: If the number was one in above step, we will give informative message popup “1 is neither Prime nor Composite”.
Line 05: Here we will check if the number is initial or not.
Line 06: If the number was initial in above step, we will give informative message popup “Input cannot be empty or 0”.
Line 07: If all the above condition will fail, then we will execute the later lines.
Line 08: Here we have added a while condition which will run until lv_check is less than or equal to the half of the entered number. It is checked, because a prime number must not be divisible to any number apart of itself and 1. To check that we divide it by all the number that is equal to or less than its half. And why half, it is because no number is divisible by a number greater than its half. E.g. 10 can never be divided by 6 i.e. greater than its half i.e. 5.
Line 09: Here we check if the number is divisible by lv_check or not. For every number, we divide it from 2 to its half with the help of lv_check. If it divides the number, then we set the flag 1 else the flag remains 0. After every check we increment the value of lv_check until it is equal to half of the entered number.
Line 10 and later: We have later checked if the flag is 0 or 1. And, if the flag remained 0, we show in output ‘Prime’ else ‘Not Prime : Composite’.
That’s it, in this way we have written successfully Prime Number Program in ABAP,