Sunday, July 16, 2017

Write a program that generates numbers between the range 0-25 and display the average of the prime numbers that are generated.

/**
 * Created by Jo on 7/10/2017.
 * For more exercises and lessons, visit http://shegertech.blogspot.com/
 * Chapter 7, Exercise 1
 */

public class Q1Solution {

    double averageOfPrimeNumbers() {
        double average = 0.0d;
        boolean flag;
        int half = 0, sum = 0, count=0;
        for (int i = 2; i <= 10; i++) {
            half = i / 2;
            flag = true;
            for (int j = 2; j <= half; j++) {
                if (i % j == 0) {
                    flag = false;
                }
            }
            if (flag) {
                sum += i;
                count++;
            }
        }

        average = (double) sum / count;
        return average;
    }

    public static void main(String[] args) {

        Q1Solution q1 = new Q1Solution();
        double average = q1.averageOfPrimeNumbers();
        System.out.println("The average is " + average);
    }
}

Share: