I need to implement a recursive function that returns 1 if the number is prime or 0 otherwise. The homework problem says that I can’t use ‘%’ mod. Haskell should be something like this… I’m not sure.
isprime x = prime(x sqrt(x))
prime x i = | i==1 = 1
| mod(x i)==0 = 0
| otherwise = prime(x i-1)
mod num div | num<div = n
| otherwise = mod(num-div div)
I tested an algorithm in C because I don’t have a Haskell compiler on my Mac, but there’s something wrong because it’s returning false positive on primes-1. idk why.
int main (int argc, const char * argv[]){
int a=0,b=31;
printf("\n Prime numbers between %d and %d \n",a,b);
for(int a=0; a<=b; a++){
if(isPrime(a)==0){
printf("%d, ",a);
}
}
return 0;
}
int isPrime(int x){
return prime(x, sqrt(x));
}
int prime(int x, int i){
if(i==0){
return 0;
}
else if(mod(x,i)==1){
return 1;
}
else{
return prime(x, i-1);
}
}
int mod(int num, int div){
if(num<div) return num;
else return mod(num-div, div);
}
The algorithm is returning this:
Prime numbers between 0 and 31
0, 1, 2, 3, 4, 6, 8, 12, 14, 18, 20, 24, 30,
Program ended with exit code: 0
(apparently, there’s a new policy regarding homework, viz. “If you don’t want a fully vetted, complete and testable answer, Stack Overflow is not the place to ask – by Tim Post”, so here goes).
Basically, your code is almost correct (1 is not a prime), sans some syntax issues.
fromIntegralis just some adaptor which lets us use anIntegralvalue as an argument tosqrtwhich expects aFloatingargument. Try using:i sqrtor:i Integraletc. at the GHCi prompt (alsoread some documentationgoogle around).But algorithmically there’s place for improvement. First of all, it’s much better to try out the divisors in the other direction, from 2 up to the number’s
sqrt, because any given number is more likely to have a smaller factor than a larger one. Second, after trying out 2, there’s no need to try out any other even number as a possible divisor. This gives usThis would normally be written down using
Bools, and a higher-order function likeandwhich captures the recursions and testing pattern (so it is not recursive anymore):There’s some redundancy in there still: after we’ve tested by 3, there’s no need to test by any of its multiples too (just like we did with 2 and evens). We really just need to test by prime factors:
Here we see the emergence of the sieve of Eratosthenes, P = {3,5, …} \ U {{p2, p2 + 2p, …} | p in P} (w/out the
2).see also: