Prime numbers are only divisible by one and the number itself. This means that if a number is a prime, it only has two factors.
A prime number is always greater than 1. For instance, 11 is a prime number because it has two factors(1, 11). However, 15 is not a prime number because it has four factors(1, 3, 5, 15).
The following code shows how to obtain prime numbers from a list.
void main() {// declare list of integersvar myList = [2,3,4,7,5,12,11,15,21,19,20];// Invoke the getPrimeNo() functiongetPrimeNo(myList);}// A function that displays the list of prime numbergetPrimeNo(List<int> numbers){List<int> primeNumbers = [];for (int val in numbers){if(isPrime(val)){primeNumbers.add(val);}}print('The prime numbers in the List: $primeNumbers');}// A function that checks if a number is prime or notbool isPrime(int number){if(number <= 1) return false; // Prime number is > 1for(int i=2; i<number; i++){if(number%i == 0) return false;}return true;}
Line 3: We define a list of integers called myList
.
Line 4: We invoke the function getPrimeNo()
that displays a list of prime numbers.
Line 9: We define the getPrimeNo()
function that takes a list of integers as a parameter.
Line 10: We define a variable called primeNumbers
which will hold the prime numbers.
Lines 11–15: We use the for...in
loop to iterate over the list of integers passed into the function getPrimeNo()
.
Line 12–14: Using the if
statement, we pass the isPrime()
function, which checks whether the number passed to the function is prime. If the isPrime()
function returns true
, the number is added to the primeNumber
list.
Line 16: We display the list of prime numbers.
Lines 20–26: We define a function called isPrime()
that checks whether a number is prime. The function takes an int
parameter called number
and returns true if the number is a prime. Otherwise, it returns false.
Free Resources