Kevin's Math Page    
     

Prime Number Java Applet

This is a Java applet which tests if a number is prime.

Here is the source code:

		
import java.applet.*;
import java.awt.*;

public class PrimeTest extends Applet
{
	boolean		isPrime = true;
	long		testedValue = 2;
	long		divisor = 1;
	TextField	theTextField;
	
	// Standard Applet procedures
	
	public void init()
	{
		setLayout(new FlowLayout(FlowLayout.LEFT));
		
		theTextField = new TextField("2", 19);
		add(new Label("Number to test:"));
		add(theTextField);
		add(new Button("Check for primality"));
	}
	
	public boolean action(Event evt, Object arg)
	{
		if ( evt.target instanceof Button )
			DoTest();
		
		return true;
	}
	
	
    public void paint(Graphics g)
    {
    	g.clearRect(0, 50, 200, 80);
        
        if ( isPrime )
       		g.drawString("" + testedValue + " is prime", 10, 60);
       	else
       		g.drawString("" + testedValue + " is divisible by " + divisor, 10, 60);
    }

	// Procedures specific to Primes
	
	public void DoTest()
	{
		String	numString;
		long	testPrime;
		
		numString = theTextField.getText();
		testPrime = Long.parseLong(numString);
		
		if ( testPrime < 2 )
			return /* nothing */ ;
			
		divisor = IsPrime(testPrime);
    	if ( divisor == testPrime )
			isPrime = true;
    	else
    		isPrime = false;

		testedValue = testPrime;
		
		repaint();
    }
    
    public long IsPrime(long testPrime)
    {
    	long	test;
    	
    	// should at least use square root
    	test = 2;
    	while ( test < testPrime )
    	{
    		if ( testPrime % test == 0 )
    			return test;
    		
    		if ( test == 2 )
	    		test++;
	    	else
	    		test += 2;
    	}
    	
        return testPrime;
    }
}

 Kevin's Math Page    
Copyright © 1996-2016 Kevin L. Gong