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

  1. Start.
  2. Read a number N from user.
  3. Initialize i with 2.
  4. If i is less than N/i, continue with next step, else go to step 7.
  5. Check if i is a factor of N. If i is a factor of N, N is not prime, return false. Go to step 8.
  6. If i is not a factor, increment i. Go to step 4.
  7. Return true.
  8. End.

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

</>
Copy
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.