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

  1. Start.
  2. Read two numbers M and N from user.
  3. For each number from M to N
    1. Initialize i with 2.
    2. If i is less than N/i, continue with next step, else go to step 3.1, and continue with next iteration.
    3. Check if i is a factor of N. If i is a factor of N, N is not prime, return false. Go to step 3.1 and continue with next iteration.
    4. If i is not a factor, increment i. Go to step 3.2.
    5. Return true.
  4. 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

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.