Exercise 8 solutions
Table of Contents
Python
e08.py
def isPrime(n): if n == 2: # n is 2, the first prime return True if n < 2: # n < 2 so not prime return False if (n % 2) == 0: # n is an even number return False # test every odd number from 3 to sqrt(n) i=3 while (i <= n**(0.5)): if (n % i) == 0: # after division is the remainder zero? return False # if yes then it's not prime i = i + 2 return True # if we found none then it is prime x = int(raw_input("Enter a number: ")) print "%d is prime: %r" % (x, isPrime(x))
MATLAB / Octave
isPrime.m
function b = isPrime(x) if x == 2 % x is 2, the first prime b = true; elseif x < 2 % x < 2 so not prime b = false; elseif mod(x,2) == 0 % x is an even number b = false; else % test every odd number from 3 to sqrt(n) b = true; i = 3; while (i <= sqrt(x)) if mod(x,i) == 0 % after division is the remainder zero? b = false; % if yes then it's not prime return end i = i + 2; end end
e08.m
x = floor(input('Enter a number: ')); disp([num2str(x), ' is prime: ',num2str(isPrime(x))]);
R
e08.R
isPrime <- function(x) { if (x == 2) { # x is 2, the first prime return (TRUE) } if (x < 2) { # x < 2 so not prime return (FALSE) } if ((x %% 2) == 0) { # x is an even number return (FALSE) } # test every odd number from 3 to sqrt(n) i <- 3 while (i <= sqrt(x)) { if ((x %% i) == 0) { # after division is the remainder zero? return (FALSE) # if yes then it's not prime } i <- i + 2 } return (TRUE) # if we found none then it is prime } x <- as.integer(readline("Enter a number: ")) cat (x, "is prime:", isPrime(x), "\n")
C
e08.c
// to compile: gcc -o e08 e08.c // #include <stdio.h> int isPrime(int x) { if (x == 2) { return 1; } else if (x < 2) { return 0; } else if ((x % 2) == 0) { return 0; } int i; for (i=3; (i*i)<x; i+=2) { if ((x % i) == 0) { return 0; } } return 1; } int main(int argc, char *argv[]) { int x; printf("Enter a number: "); scanf("%d", &x); printf("%d is prime: %d\n", x, isPrime(x)); return 0; }