I am trying to translate this C code to OCaml code, which should check if the input int is prime number or not. My C code works, but my ocaml code doesn't even run.
void is_prime(int pri){
int a=2;
int b=poww(a,2);
while(b<=pri){
int resu=pri%a;
if(resu==0) {
printf("False");
return 0;
}
a++;
b=poww(a,2);
}
printf("True");
}
And this is my OCaml code:
let is_prime n =
let a= ref 2 in
let b= ref (pow !a 2) in
let c= ref true in
while !b<n do
let resu= (n mod !a) in
if resu=0 then c:=false;
a:=!a+1;
b:=(pow !a 2);
done in
if c=false then false
else true
;;
What I want is an OCaml code takes an int as input and output a boolean. pow in my OCaml code is an existing function pow ab (where a and b are int and output a^b). For some reason, the code doesn't work...
Update: problem solved New Ocaml code that works:
let is_prime n =
if n>1 then
let a= ref 2 in
let b= ref (pow !a 2) in
let c= ref true in
while !b<n do
(*ignore (Printf.printf "abc");*)
let resu= (n mod !a) in
if resu=0 then c:=false;
a:=!a+1;
b:=(pow !a 2);
done;
if !c then true
else false
else raise Domain
;;
One possibility: your C code has while (b <= pri)
. Your OCaml code has while !b < n
. The meanings of <=
in C and <
in OCaml are different.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.