Example sheet 4: Prime numbers
Task: Write a program that prints out all of the prime numbers between 2 and some integer n (my solution is overleaf).
A prime number is a number that is divisible only by 1 and itself. The first 5 prime numbers are 2,3,5,7,11.
Breaking the problem down 1:
Copyright By PowCoder代写 加微信 powcoder
In order to be able to write a program that can list prime numbers, we need to be able to decide if any particular number is prime or not. This feels like something that could sit inside its own method.
Below is the template for a method to check if a number is prime or not. Task: Complete the method declaration.
Breaking the problem down 2:
It’s easier to determine if something is *not* a prime — we simply have to find a number that it perfectly divides by that is not 1 or itself. Task: write an if statement that will check if a number (m) is divisible by another number (i).
Task: Embed this statement within a loop (from 2 to m-1) in the method below. The method should return false if it finds any number that divides perfectly. If it finds none, it should return true.
public static __________isPrime(____________) {
Task: Fill in the following method that will print all of the primes between 2 and n (using isPrime)
Public static void listPrimes(int n) {
My full solution
public class Primes {
public static void main(String[] args) {
listPrimes(1000); }
public static void listPrimes(int n) { /*
* Lists all primes from 2 to n (inclusive)
for(int i=2;i<=n;i++) { if(isPrime(i)) {
number", i);
String line = String.format("%5d is a prime System.out.println(line);
public static boolean isPrime(int m) { // assumes n >= 2
for(int i=2;i