Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get prime numbers and total prime numbers in range

Tags:

java

I am a beginner in Java. I am writing this program to show all prime numbers in between the number supplied from the user.

Current output is:

2, 3, 5, 7, Count: 4

But, i want the output to be like:

"The number of prime is: "+count+", and they are: " followed by all the numbers separated by comma

package com.example.test;

import java.util.Scanner;

public class PrimeTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out
                .println("Enter the number till which the prime numbers are to be calculated: ");
        int input = scanner.nextInt();

        int count = 0;

        // loop through the numbers one by one
        for (int i = 2; i < input; i++) {

            boolean isPrimeNumber = true;

            // check to see if the number is prime
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isPrimeNumber = false;
                    break; // exit the inner for loop
                }
            }

            // print the number if prime
            if (isPrimeNumber) {
                count++;
                System.out.print(i + ", ");

            }

        }
        System.out.println("Count: " + count);
    }

}
like image 412
t_godd Avatar asked Mar 19 '14 14:03

t_godd


1 Answers

You have to store the values, for example like this :

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class PrimeTest {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number till which the prime numbers are to be calculated: ");
        int input = scanner.nextInt();
        List<Integer> primes = new ArrayList<>();

        // loop through the numbers one by one
        for (int i = 2; i < input; i++) {
            boolean isPrimeNumber = true;

            // check to see if the number is prime
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isPrimeNumber = false;
                    break; // exit the inner for loop
                }
            }

            // print the number if prime
            if (isPrimeNumber) {
                primes.add(i);
            }
        }
        System.out.println("The number of prime is: " + primes.size() + ", and they are: " + primes.toString());
    }
}
like image 106
libik Avatar answered Nov 06 '22 07:11

libik