How to find the primes in a list in Dart

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).

Example

The following code shows how to obtain prime numbers from a list.

void main() {
// declare list of integers
var myList = [2,3,4,7,5,12,11,15,21,19,20];
// Invoke the getPrimeNo() function
getPrimeNo(myList);
}
// A function that displays the list of prime number
getPrimeNo(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 not
bool isPrime(int number){
if(number <= 1) return false; // Prime number is > 1
for(int i=2; i<number; i++){
if(number%i == 0) return false;
}
return true;
}

Explanation

  • 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

Copyright ©2024 Educative, Inc. All rights reserved