Problem: trial_division_optimized

Your task is to implement an efficient Primality Test using trial division up to the square root and verify its correctness in Dafny. Preconditions: The input n is a non-negative integer (simulating u64). Requirements: Implement the method check_prime which returns true if n is prime and false otherwise. (1) Algorithm: You must optimize the loop bound. Instead of checking up to $n-1$, stop checking once the iterator i satisfies $i \times i > n$. (2) Functional Correctness: You must verify that checking only up to $\sqrt{n}$ is sufficient to determine primality for the whole range. Verification Challenges: Non-Linear Loop Bound: The loop condition i * i <= n involves multiplication. SMT solvers often struggle with this. You may need to carefully structure the invariant to avoid timeouts. Mathematical Lemma: The core of the proof depends on a number-theoretic fact: If $n$ is composite, it has a factor less than or equal to its square root. You will likely need to state and prove this as a helper lemma to convince the verifier that stopping early is safe.

// Following is the block for necessary definitions
// <preamble>
predicate divides(d: int, n: int)
  requires d != 0
{
  n % d == 0
}

predicate is_prime(n: int)
{
  n > 1 &&
  forall d :: 1 < d < n ==> !divides(d, n)
}
// </preamble>

// Following is the block for potential helper specifications
// <helpers>

// </helpers>

// Following is the block for proofs of lemmas
// <proofs>

// </proofs>

// Following is the block for the main specification
// <spec>
method check_prime(n: int) returns (res: bool)
  // Simulate u64: input is non-negative
  requires n >= 0
  ensures res == is_prime(n)
// </spec>
// <code>
{
  // Implement and verify the optimized algorithm that checks divisibility up to sqrt(n)
}
// </code>

method Main() {
}