Play Games

Search This Blog

Monday, August 8, 2022

Display prime numbers with in the range

Solution: A prime number is a number that is only divisible by 1 and itself.

Example: 2, 3, 5, 7, 11 etc are prime numbers

Example:

Apex class:

public class PrimeNumberController {

    public static void displayPrimeNumbers(Integer startingNumber,Integer endNumber) {

        List<Integer> lstPrimeNumber = new List<Integer>();

        for(integer i= startingNumber ; i<=endNumber ; i++) {

            if(checkPrimeNumber(i) == true) {

                lstPrimeNumber.add(i);

            }

        }

        System.debug('The Prime Numbers are: '+lstPrimeNumber);

    }

    public static Boolean checkPrimeNumber(integer num) {

        Boolean isPrimeNumber = true;

        if(num <2) {

            isPrimeNumber = false;

        } else {

            for(integer i = 2; i <num; i++) {

                integer m = math.mod(num,i);

                if(math.mod(num,i) == 0) {

                    isPrimeNumber = false;

                }

            }

        }

        return isPrimeNumber;

    }

}

Run the following from developer console

PrimeNumberController.displayPrimeNumbers(40,50);

Output:



No comments:

Post a Comment