In this example you will learn how to check if a number is prime or composite in R Programming. You will also print a list of prime numbers from 2 to a given number.
A prime number is defined as any positive number which is only divisible by 1 and itself. Any number which is not prime is called composite. 1 is considered as neither prime nor composite. Example of prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, .....
If you want to check if a number is prime or not, simply see its factors. If it has only two factors, i.e 1 and the number itself then it is a prime number.
Check if 10 is a prime number. The factors of 10 are 1,2,5,10. Hence it is not a prime number
Check if 17 is a prime number. The factors of 17 are 1,17. Hence it is a prime number.
To find if a number is prime or not, we define a function isprime.
In this example the function isprime() checks if a number is prime. First a variable lim is created which is half of the original number. It is to cut iteration of for loop in to half as there are no more factors possible after half of a number. The variable prime contains T or TRUE initially, and if the number is not prime, it will be changed into F.