Java program to print N prime numbers and find sum and average


Program

package com.candidjava;

import java.util.Scanner;

public class PrimeNumberUptoN
{

	private static double a;

	public static void main(String args[])
	{

		int number = 2;
		int count = 0;
		double sum = 0;

		Scanner sc = new Scanner(System.in);
		System.out.println("The number n is");
		int n = sc.nextInt();

		while (count < n)
		{
			if (isPrimeNumber(number))
			{

				System.out.print(number+" ");
				sum += number;
				a++;

				count++;
			}
			number++;
		}

		System.out.println("\n Sum = "+sum);

		double average = (sum / a);
		System.out.println("\n Average = "+average);
	}

	private static boolean isPrimeNumber(int number)
	{

		for (int i = 2; i <= number / 2; i++)
		{
			if (number % i == 0)
			{
				return false;
			}
		}
		return true;
	}
}
Output
The number n is
20
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 

Sum = 639.0
Average = 31.95


Related Post

Comments


©candidjava.com