简体   繁体   中英

Program to display the first 100 prime numbers is not displaying

I am new to Java and I have been searching for an answer around the internet for a good hour but could not find anything.

I'm trying to create a program that displays the first 100 prime numbers in this format:

First One Hundred Primes:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541

EDIT: ^ This format is supposed to be right-justified as well.

I'm not sure why it's not displaying anything when I try to run it in the console. And no, my code is not completely finished. Please help me on why it's not displaying and anything else I've done wrong, thanks! :)

This is my code right now:

public class PrimeNumbers {

    public static void main(String[] args) {
        final int DIVISOR = 1;
        boolean isPrime;
        int test1 = 0;
        int test2 = 0;
        int num = 1;
        int count = 0;

        while(count < 101) {
            test1 = num/DIVISOR; //divides number by 1
            test2 = num%num; //gets remainder of number

            if (test1 == num && test2 == 0 && num > 1) //checks if test 1 is the same as num, test2 equals to 0 and if num is greater than 1
                isPrime = true;
            else
                isPrime = false;

                if (isPrime == true) {
                    System.out.format("%3.3f");
                    System.out.println("First One Hundred Primes:");
                    System.out.print(num);
                }
        }

    }
}

So basically what you have to do is have a function which checks whether a number is prime or not. After that, you have to start counting from 2 and pass each number to that function. If it returns true, print it and record the fact that you found a prime. When you did this 100 times, you can stop. The following code implements exactly this:

public class OneHundredPrimes
{
    public static boolean isPrime(int x)
    {
        for (int i = 2; i <= Math.sqrt(x); i++) {
            if (x % i == 0) {
                return false;
            }
        }

        return true;
    }

    public static void main(String[] args)
    {
        int currentNumber = 2;
        int primesFound = 0;

        while (primesFound < 100) {
            if (isPrime(currentNumber)) {
                primesFound++;

                System.out.print (currentNumber + " ");
                if (primesFound % 10 == 0) {
                    System.out.println();
                }
            }

            currentNumber++;
        }
    }
}

If something is unclear, ask.

I think you should rethink the design of your code:

  • create a method boolean isPrime(int i) that returns true if i is prime, false if not.
  • test that the method return the expected value (true/false) for a few numbers to convince yourself that your algorithm works
  • loop over the integers from 1 to Integer.MAX_VALUE and check each of them with the method above: if it is prime, print it and increment your count.
  • stop when count has reached 100.

You should increment num in every cycle, and you should also increment count whenever you have found a prime.

Oh and your DIVISOR can't be 1 and can't be final :) For your every number you should try and divide it by divisor values between 2 and number-1 - to find out if it's a prime number.

If this is homework, please tag accordingly.

Consider your while loop. How is the loop exiting? Consider your counters, when are they incremented?

Prime Number:

A Prime Number can be divided evenly only by 1 or itself. 
And it must be greater than 1.

Based on this you need to modify your program:-
1. Take 2 loops
2. One is outer loop for the count <= 100
3. One is inner loop which checks whether number is prime or not and display it

class StackOfInteger {
    private int[] elements;
    private int size;
    public static final int DEFAULT_CAPACITY = 2;

    public StackOfInteger() {
        size = 0;
        elements = new int[DEFAULT_CAPACITY];
    }

    public StackOfInteger(int capacity) {
        elements = new int[capacity];
    }

    public int push(int value) {
        if (size >= elements.length) {
            int[] temp = new int[elements.length * 2];
            System.arraycopy(elements, 0, temp, 0, elements.length);
            elements = temp;
        }
        return elements[size++] = value;
    }

    public int pop() {
        return elements[--size];
    }

    public int peek() {
        return elements[size - 1];
    }

    public boolean empty() {
        return size == 0;
    }

    public int getSize() {
        return size;
    }
}

public class JavaApplication82 {
    public static void main(String[] args) {
        // TODO code application logic here
        String getInput = JOptionPane.showInputDialog("Get your shit !");
        int input = Integer.parseInt(getInput);
        getPrime(input);
    }

    public static void getPrime(int getInput) {
        StackOfInteger stack = new StackOfInteger();
        int dem = 4;
        stack.push(2);
        stack.push(3);
        do {
            if (isPrime(dem) == true) {
                stack.push(dem);
                dem++;
            } else
                dem++;
        } while (dem <= getInput);
        while (!stack.empty())
            System.out.println(stack.pop() + " ");
    }

    public static boolean isPrime(int getNumber) {
        int dem1 = 0;
        int[] arrayTest = new int[getNumber];
        for (int i = 2; i <= getNumber; i++) {
            arrayTest[i] = i;
        }
        for (int i = 2; i < getNumber; i++) {
            if (getNumber % arrayTest[i] == 0)
                dem1++;
            else
                continue;
        }
        if (dem1 != 0)
            return false;
        else
            return true;
    }
}

another way would be the separate the prime method from from main (based on first solution) note: this is without the text formatting:

public class Primes
{
    public static boolean isPrime (int x)
    {
        for (int i = 2; i <= Math.sqrt (x); i++)
        {
            if (x % i == 0)
            {
                return false;
            }
        }
        return true;
    }

    public static void main (String[] args)
    {
    new Primes().findprimes(100);  // <<--here you can choose whatever k prime
    }

    public void findprimes (int k){
    for (int i = 2, primesfound = 0; primesfound < k+1 ; i++)
    {
        if (isPrime (i))
        {
            primesfound++;
            System.out.print (i + " ");
        }
    }   
  }
}
public class prime {
    public static int Prime(int n,int counter)
    {
        if(n<=3 && n>0)
        {
            return n;
        }
        if((n-counter)==n || n%(n-counter)>0){
            counter++;
            return Prime(n,counter);
        }
        else if((n-counter)>1 && n%(n-counter)==0){
            return 0;
        }
        else
            return n;
    }
    public static void main(String[] args) {
        int k=0,found=0;
        for(int i=1;found<100;i++){
            k=Prime(i, 0);
            if(k>0){
               found++;
               System.out.println(k);
            }
        }
    }
}
package com.mehmood.nisar;

public class Myclass {

    public static void main(String [] args)
    {
        int status = 0;

        for (int i = 2; i < 100; i++) {

            status =0;
            for (int j = 2; j < i; j++) {

                if(i %2 == 0)
                {
                    status = 1;
                    break;
                }

                try {
                    if(i % j == 0)
                    {
                        status = 1;
                        break;
                    }
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            }//break;

            if(status == 0)
            {
                System.out.println(i);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM