## Prime Number Checker |
## Loading... |

An exercise aimed at combining loops and if statements, here’s what it needs to do:

Write a function called “isPrime” that returns True if a number given to it is prime, and False otherwise.
Outside of “isPrime” ask the user for a number and save it. Output whether the given number is prime or not by using the method function/method “isPrime”. |

*Try not to look at the answers until you’ve solved the problem. A*

*lso note that this code has not been error proofed and thus any input that is not a positive integer could cause it to crash or misbehave.*

## C#:## Show Code >>//This function returns True if number is prime static private bool isPrime(int number) { for (int i = 2; i < number; i++) if (number % i == 0) return false; return true; } //Ask for and save the users number here Console.WriteLine("What number would you like to check is prime?"); //C# reads in strings which must be converted to integers String myNumberAsAString = Console.ReadLine(); int myNumber = Convert.ToInt32(myNumberAsAString); //check if the number is prime and say which it is. if (isPrime(myNumber)) Console.WriteLine(myNumber + " is prime."); else Console.WriteLine(myNumber + " is not prime."); Console.WriteLine("Press enter to exit"); Console.ReadLine(); |

## Java:## Show Code >>//This function returns True if number is prime static private boolean isPrime(int number) { for (int i = 2; i < number; i++) if (number % i == 0) return false; return true; } Scanner sc = new Scanner(System.in); //used for reading in data //Ask for and save the users number here System.out.println("What number would you like to check is prime?"); int myNumber = sc.nextInt(); //check if the number is prime and say which it is. if (isPrime(myNumber)) System.out.println(myNumber + " is prime."); else System.out.println(myNumber + " is not prime."); System.out.println("Exiting now"); |

## Python:## Show Code >>#This function returns True if number is prime def isPrime(number): for i in range (2,number-1): if (number % i == 0): return False return True #Ask for and save the users number here myNumber = int(input("What number would you like to check is prime?")) #check if the number is prime and say which it is. if(isPrime(myNumber)): print(myNumber, "is prime.") else: print(myNumber, "is not prime.") |

Updated 24 January 2015 by Matthew F.