Dart challenge solution I did not understand well

I am reading a book to learn Dart, there are challenges that they share on GitHub. The challenge I am interested in is here: Challenge 2

I could not understand this challenge well, below I share the questions and the solution provided.

/// Challenge 2: Prime Time
///
/// Write a function that checks if a number is prime.
///
/// First, write a function with the following signature to determine if one
/// number is divisible by another:
///
/// ```
/// bool isNumberDivisible(int number, int divisor)
/// ```
///
/// The modulo operator `%` will help with that.
///
/// Then, write the function that returns `true` if prime and `false` otherwise:
///
/// ```
/// bool isPrime(int number)
/// ```
///
/// A number is prime if it's only divisible by 1 and itself. Loop through the
/// numbers from 1 to the number and find the number's divisors. If it has any
/// divisors other than 1 and itself, it's not prime.
///
/// Check the following cases:
///
/// ```dart
/// isPrime(6); // false
/// isPrime(13); // true
/// isPrime(8893); // true
/// ```
///
/// Here are a few more hints:
///
/// - Numbers less than zero are not considered prime.
/// - Use a `for` loop to look for divisors. You can start at 2 and if you
/// end before the number, return false.
/// - If you're clever, you can loop from 2 until you reach the square root
/// of the number. Add the following import to the top of the file to access
/// the `sqrt` function:
///
/// ```dart
/// import 'dart:math';
/// ```
void challenge2() {
  bool isNumberDivisible(int number, int divisor) => number % divisor == 0;

  bool isPrime(int number) {
    for (var i = 2; i <= sqrt(number); i++) {
      if (isNumberDivisible(number, i)) {
        return false;
      }
    }
    return true;
  }

  print(isPrime(6));
  print(isPrime(13));
  print(isPrime(8893));
}

My question is, why the solution did not use if then if else and why this code works even if we wrote return true outside of if statement.

Besides, why it does each time return true at the end as it is outside if statement and for loop.

I searched the internet for a website that run line by line Dart code to understand it better but I could not find one.

All of the possible numbers need to be looped over until a match is found (ie it’s prime). If that match is found, can stop the loop and exit, returning true.

If every number has been checked (ie the loop is complete) and no match was found, then it’s not prime. Not possible to tell for sure until that point

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.