Search code examples
clojure

Fermat's little Theorem Clojure


I am trying to write a clojure function for Fermat's little theorem.

I am breaking the problem down and trying to complete it step by step.

The first thing I want to write is the code to answer this part of my problem:

Given a number n, pick a random number a that is less than n. Compute the remainder of a^n modulo n.

Here is the code I have written so far:

  (defn exp [a n]
  (reduce * (repeat n a)))

(mod (exp 3 5) 5)

This seems to work correctly and can test for prime numbers. However I now want to put this inside a function and get a to be selected at random. Is there a simple way of getting random integers in clojure?

Any help much appreciated.


Solution

  • You probably want the rand-int function:

    (defn rand-mod [n]
      (mod (exp (rand-int n) n) n))