Contents

Find composite number (with.Java)

   Feb 11, 2024     2 min read

This article examines the problem of “Finding composite numbers.”

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Let’s look at the problem first.

problem

A number with three or more divisors is called a composite number.

When a natural number n is given as a parameter, complete the solution function so that it returns the number of composite numbers less than n.

Restrictions

  • 1 ≤ n ≤ 100

Input/Output Example

nresult
105
158

My solution to the problem

class Solution {
     public int solution(int n) {
         int answer = 0;
         int count = 0;
         for(int i = 1; i <= n; i++){
             for(int j = 1; j <= i; j++){
                 if(i % j == 0){
                     count++;
                 }
             }
             if(count > 2){
                 answer++;
             }
             count = 0;
         }
         return answer;
     }
}

Solution explanation

solution(int n): Determines whether each number within the given range is prime, and if so, increments the answer.

count: A variable that counts the number of divisors of each number. For decimal numbers, the number of divisors must be 2.

Use the for statement to repeat numbers from 1 to n, and use the nested for statement to find the divisors of each number.

In the inner for statement, if(i % j == 0) is a condition that checks whether j is a divisor of i.

If the number of factors exceeds 2, the number is not prime.

Problem Solving: Solve problems using the simple method of finding the number of prime numbers within a given range.

Intuitive: The code is intuitive and easy to understand.

Although the code is simple, it does not use an efficient prime number discrimination algorithm, so performance may not be good for large input values.

To improve this, it is recommended to use an efficient decimal discrimination algorithm.