Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(* Problem 5 *) OCAML Given: exception BadDivisors of int let bad_divisors n = r

ID: 3750020 • Letter: #

Question

(* Problem 5 *)

OCAML

Given:

exception BadDivisors of int

let bad_divisors n = raise (BadDivisors n)

let count_divisors n =

(* Write the function count_divisors, which takes one parameters n and

returns the number of divisors that n has (including 1 and n): *)

(*

let _ = count_divisors 17 (* 2 -- 17 divides only 1 and 17 *)

let _ = count_divisors 4 (* 3 -- 4 divides 1, 4, and 2 *)

let _ = count_divisors 18 (* 6 -- 18 divides 1, 18, 2, 3, 6, and 9 *)

*)

(* The type signature for count_divisors is: *)

(* count_divisors : int -> int *)

(* count_divisors should call the function (bad_divisors n) defined

above if n <= 0 *)

(* You can write as many "helper" functions as you need using

"let..in" or just "let". *)

(* After writing count_divisors above, uncomment the following lines

to test your code. (Note: your code is not necessarily completely

correct just because it passes these 3 tests.)

let _ = assert (count_divisors' 17 = 2)

let _ = assert (not (count_divisors' 4 = 2))

let _ = assert (count_divisors' 18 = 6)

*)

Explanation / Answer

# let bad_divisors n = raise (BadDivisors n)

# let count_divisors n =

if n<=0 then bad_divisors n else

(

let count=0

let sqrtn=(n/2)

for i=1 to i<(sqrtn+1) do

(*

If divisors are equal,

count only one

*)

if n%i=0 then

(

if n/i=i

then

count=count+1

(* Otherwise count both

*)

else count=count+2

)

done

count

)

;;

val count_divisors : int -> int = <fun>

let _ = assert (count_divisors' 17 = 2)

let _ = assert (not (count_divisors' 4 = 2))

let _ = assert (count_divisors' 18 = 6)