problem: 2.8


 Question 2.8: Create a function that finds how many prime numbers there are, up to the given integer.

Examples

primeNumbers(10) ➞ 4

// 2, 3, 5 and 7

primeNumbers(20) ➞ 8

// 2, 3, 5, 7, 11, 13, 17 and 19

primeNumbers(30) ➞ 10

// 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29


Solution: 

package com.company;

import java.util.Scanner;

public class lab2Problem08 {

        static int primeNumber(int n) {
            int d=0;
            for (int i = 2; i <= n; i++) {
                int c = 0;
                for (int j = 2; j <= i; j++) {
                    if (i % j == 00) {
                        c++;
                    }
                }
                if (c < 2) {
                    d++;
                }
            }
            return d;
        }
        public static void main (String[]args){
        Scanner Obj = new Scanner(System.in);
        while(true){
        System.out.println("Input a number: ");
        int n = Obj.nextInt();

        int r = primeNumber(n);
            System.out.println("total prime number is: "+ r);
        for (int i = 2; i <= n; i++) {
            int c = 0;
            for (int j = 2; j <= i; j++) {
                if (i % j == 00) {
                    c++;
                }
            }
            if(c < 2)
            {
                System.out.print(" "+i);
            }
        }
            System.out.println();


    }
    }
}

Previous Post Next Post