Dart Program – Check Prime Number
In this tutorial, we shall write a function in Dart language, to check if given number N is prime number or not.
Algorithm
- Start.
- Read a number
N
from user. - Initialize
i
with 2. - If
i
is less thanN/i
, continue with next step, else go to step 7. - Check if
i
is a factor ofN
. Ifi
is a factor ofN
,N
is not prime, return false. Go to step 8. - If
i
is not a factor, incrementi
. Go to step 4. - Return
true
. - End.
ADVERTISEMENT
Dart Program
In the following program, we shall write a function isPrime()
, using the above algorithm. This function takes a number as argument, then check if the number is prime or not, and returns a boolean value. The function returns true if the number is prime, else it returns false.
main.dart
import 'dart:io'; bool isPrime(N) { for (var i = 2; i <= N / i; ++i) { if (N % i == 0) { return false; } } return true; } void main() { print('Enter N'); var N = int.parse(stdin.readLineSync()!); if (isPrime(N)) { print('$N is a prime number.'); } else { print('$N is not a prime number.'); } }
Output#1
Enter N 11 11 is a prime number.
Output#2
Enter N 25 25 is not a prime number.
Conclusion
In this Dart Tutorial, we learned how to check if given number is Prime number or not, in Dart programming, with examples.