Mencari Bilangan Prima dengan Bahasa Java

bilangan prima java

Sama seperti artikel saya Program untuk Mencari Bilangan Prima dengan Visual Foxpro, kali ini saya coba menerjemahkan ke bahasa java. Berikut adalah contoh mendapatkan bilangan prima dari 1 sampai dengan 100.

/**
 * 16-11-2012 22:53
 * @by thesuhu
 */
public class BilanganPrima {

    private static int i;
    private static int k;
    private static int n;

    public static String getPrima(int awal, int akhir) {
        String hasil = "";
        boolean isPrima = false;
        for (i = awal; i <= akhir; i++) {
             if (i > 1) {
                isPrima = true;
                if (i == 2) {
                    isPrima = true;
                } else {
                    n = i - 1;
                    for (k = 2; k <= n; k++) {
                        if (i % k == 0) {
                            isPrima = false;
                        }
                    }
                }
            }

            if (isPrima == true) {
                if ("".equals(hasil)) {
                    hasil = hasil + i;
                } else {
                    hasil = hasil + "," + i;
                }
            }
        }
        return hasil;
    }

    public static void main(String[] args) {
        System.out.println(BilanganPrima.getPrima(1, 100));
    }
}
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s