Dart Program – Print Prime Numbers present in Given Range
In this tutorial, we shall write a function in Dart language, to print all the prime numbers present int the range between M and N, including M and N, where M < N.
Algorithm
- Start.
- Read two numbers
MandNfrom user. - For each number from M to N
- Initialize
iwith 2. - If
iis less thanN/i, continue with next step, else go to step 3.1, and continue with next iteration. - Check if
iis a factor ofN. Ifiis a factor ofN,Nis not prime, return false. Go to step 3.1 and continue with next iteration. - If
iis not a factor, incrementi. Go to step 3.2. - Return
true.
- Initialize
- End.
Dart Program
In the following program, we shall write a function printPrimeNumbers(), using the above algorithm. This function takes two numbers as arguments, and print all the prime numbers present from M to N.
main.dart
</>
Copy
import 'dart:io';
void printPrimeNumbers(M, N) {
a:
for (var k = M; k <= N; ++k) {
for (var i = 2; i <= k / i; ++i) {
if (k % i == 0) {
continue a;
}
}
stdout.write(k);
stdout.write(' ');
}
}
void main() {
print('Enter M');
var M = int.parse(stdin.readLineSync()!);
print('Enter N');
var N = int.parse(stdin.readLineSync()!);
print('Prime Numbers in the Given Range');
printPrimeNumbers(M, N);
}
Output#1
Enter M
11
Enter N
22
Prime Numbers in the Given Range
11 13 17 19
Output#2
Enter M
25
Enter N
50
Prime Numbers in the Given Range
29 31 37 41 43 47
Conclusion
In this Dart Tutorial, we learned how to print Prime numbers present in the given range, in Dart programming, with examples.
