본문 바로가기
Language/Algorithm

Prime Number Count

by Zayne 2023. 12. 12.

Example

Input : 20
Output : 8

 

My answer :

import java.util.Scanner;

class PrimeNumberCounter {
	public static void main(String[] args) {
		PrimeNumberCounter t = new PrimeNumberCounter();
		Scanner kb = new Scanner(System.in);
		int n = kb.nextInt();
		System.out.println(t.solution(n));
	}

	int solution(int n) {
		int answer = 0;
		int[] tmp = new int[n];

		for(int i = 0; i < n; i++) {
			tmp[i] = i + 1;
		}

		for(int j : tmp) {
			int cnt = 0;
			for(int k = 1; k <= j; k++) {
				if(j % k == 0) cnt ++;
			}
			if(cnt == 2) answer++;
		}

		return answer;
	}
}

 

  1. The program starts by creating an instance of the PrimeNumberCounter class and a Scanner object to read input from the user.
  2. It reads an integer n from the user.
  3. The solution method is called with the input n, and the result is printed to the console.
  4. Inside the solution method:
    • An array tmp of size n is created.
    • The elements of the array are initialized with values from 1 to n.
    • A loop iterates through each element of the array.
    • For each element j, another loop counts the number of divisors it has.
    • If the count is 2 (only divisible by 1 and itself), the answer variable is incremented.
  5. The final count of prime numbers is returned, and it is printed to the console.

'Language > Algorithm' 카테고리의 다른 글

Count Consecutive 1s Total  (0) 2023.12.14
Number Reversal Prime Check  (0) 2023.12.13
Fibonacci series  (4) 2023.12.07
Rock Paper Scissors Game  (2) 2023.12.06
Increasing Sequence Counter  (0) 2023.12.05