Problem Description
We are trying to find the number of non-perfect square numbers among integers from 1 to N. A perfect square refers to a number obtained by squaring an integer. For example, 1, 4, 9, 16, 25, etc., are all perfect squares. On the other hand, 2, 3, 5, 6, 7, 8, 10, etc., are not perfect squares.
Input Format
The first line contains the integer N (1 ≤ N ≤ 106).
Output Format
Print the count of non-perfect square numbers among integers from 1 to N.
Sample Input
10
Sample Output
7
Problem Solving Process
To solve this problem, we need to subtract the count of perfect squares from the total count of numbers. The following steps outline the procedure.
Step 1: Identify the range of perfect squares
Perfect squares are generated in the form of 1, 4, 9, 16, … etc. If N is 10, the perfect squares are 1(12), 4(22), and 9(32). In this case, there are a total of 3 perfect squares.
Step 2: Calculate the count of perfect squares
For N, we need to find the maximum integer k such that k2 <= N. This k can be calculated as the integer part of √N
.
Step 3: Derive the result
The total count of numbers is N, and the count of perfect squares is k. Therefore, the count of non-perfect square numbers can be calculated as N - k
.
Implementation Code (Swift)
func countNonPerfectSquares(N: Int) -> Int {
// Calculate k to find perfect squares among numbers from 1 to N.
let k = Int(sqrt(Double(N)))
// Calculate the count of non-perfect square numbers.
return N - k
}
// Example execution
let N = 10
print(countNonPerfectSquares(N: N)) // Result: 7
Complexity Analysis
This algorithm has a time complexity of O(1)
. The operation of calculating the square root for a given N is performed in constant time, making it very efficient. Memory usage is also limited to a constant, so this problem operates reliably even with large inputs.
Post Analysis
This problem allowed us to understand the concept of perfect squares along with the efficiency of square root calculations. We also learned how to solve complex problems through very simple calculations.
Conclusion
In the process of solving algorithm problems, it is important to understand the problem, devise a step-by-step solution, and implement it efficiently. This process will greatly help in dealing with various types of algorithm problems. In the next lecture, we will tackle more complex algorithm problems. Thank you!