Display prime numbers using Apex code #inSalesforce
public static List<Integer> getPrimeNumbers(Integer n) {
List<Integer> primeNumbers = new ArrayList<Integer>();
primeNumbers.add(2);
for (int i = 3; i <= n; i++) {
boolean isPrime = true;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primeNumbers.add(i);
}
}
return primeNumbers;
}
public static void displayPrimeNumbers(Integer n) {
List<Integer> primeNumbers = getPrimeNumbers(n);
for (int i = 0; i < primeNumbers.size(); i++) {
System.debug(primeNumbers.get(i));
}
}
}
This code first creates a class called PrimeNumbers that has two static methods: getPrimeNumbers() and displayPrimeNumbers().
The getPrimeNumbers() method takes an integer as input and returns a list of prime numbers up to that number. The code for this method first adds the number 2 to the list of prime numbers. Then, it iterates from 3 to the number passed in as input. For each iteration, the code checks if the number is prime. A number is prime if it is only divisible by itself and 1. If the number is prime, the code adds it to the list of prime numbers.
The displayPrimeNumbers() method takes an integer as input and displays the prime numbers up to that number. The code for this method first calls the getPrimeNumbers() method to get the list of prime numbers. Then, it iterates through the list and prints each prime number to the console.
To use this code, you would first need to create a new Apex class and paste the code into the class. Then, you would need to call the displayPrimeNumbers() method, passing in the number of prime numbers that you want to display. For example, the following code would display the first 10 prime numbers:
PrimeNumbers.displayPrimeNumbers(10);
This code would print the following numbers to the console: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29.
Comments
Post a Comment