Understanding Computer Programming

Osher Lifelong Learning Institute
University of Illinois, Urbana-Champaign

Scott Badman, Instructor


Topic: Prime algorithm implemented in Java

February 11, 2016


import java.io.*;

public class Prime
{
    public static void main(String[] args)
    {
        int number;
        boolean prime;

        System.out.println("Please enter a number to see if it is a prime:");
        number = Integer.valueOf(System.console().readLine());

        if (number < 0 || number > 1000000)
        {
            System.out.println("Number out of range.");
        }
        else
        {
            prime = determineIfPrime(number);

            if (prime == true)
                System.out.println(number + " is a prime.");
            else
                System.out.println(number + " is not a prime.");
        }
    }

    private static boolean determineIfPrime(int number)
    {
        int remainder;
        int divisor;
        boolean prime;

        prime = true;

        if (number == 0 || number == 1)
        {
            prime = false;
        }
        else
        {
            divisor = 2;

            while (divisor < number)
            {
                remainder = modulo(number, divisor);

                if (remainder == 0)
                    prime = false;

                divisor = divisor + 1;
            }
        }
        return prime;
    }


    private static int modulo(int number, int divisor)
    {
        int remainder;
        int intermediate;

        intermediate = number;

        while (intermediate >= divisor)
        {
            intermediate = intermediate - divisor;
        }

        remainder = intermediate;

        return remainder;
    }

}


Understanding Computer Programming

Osher Lifelong Learning Institute
University of Illinois, Urbana-Champaign

Scott Badman, Instructor