Skip to main content
gamedev.net
🔒 Locked

prime and %

Started by derek7 Aug 1, 2006 at 2:25 AM 3 replies 450+ views
Original Post
derek7
derek7
How could you use modulus to write a program that checks if a number is prime?
Grain
Grain
http://www.gamedev.net/community/forums/topic.asp?topic_id=329905

also:

http://www.gamedev.net/community/forums/topic.asp?topic_id=406992
Black Knight
Black Knight
int iNum = 0;
scanf("%d",&iNum);
bool bPrime = true;
for(int i=2;i{
if(iNum%i==0){ bPrime = false; break;}

}

I dont know if it works lol im at work.
Roboguy
Roboguy
Here's some Scheme code I made a while ago (with some slight modifications), that will check if a number is prime:
(define (divisible? a b)  (= (modulo a b) 0))(define (any f xs)  (cond ((null? xs) #f)        ((f (car xs)) #t)        (else (any f (cdr xs))))); Find all primes less than n.(define (primes n)  (define (primes-loop n max primes)    (if (>= n max)        primes        (if (any (lambda (a) (divisible? n a)) primes)            (primes-loop (+ n 1) max primes)            (primes-loop (+ n 1) max (cons n primes)))))  (primes-loop 3 n '(2)))(define (in x xs)  (any (lambda (y) (equal? x y)) xs))(let ((num (read)))  (if (in num (primes (+ num 1)))      (display "The given number is prime.")      (display "The given number is not prime."))  (newline))
Rixter
Rixter
Quote:
Original post by Black Knight
int iNum = 0;
scanf("%d",&iNum);
bool bPrime = true;
for(int i=2;i{
if(iNum%i==0){ bPrime = false; break;}

}

I dont know if it works lol im at work.


If you go this route you actually only need to check up to the square root of iNum.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.