kotlin coding test course, Euler PI

1. What is the Euler Problem?

Leonardo Euler was a mathematician who made many contributions to various fields of mathematics. The Euler problems, named after him, are primarily problems that require mathematical thinking and algorithmic approaches. These problems often focus on discovering ways to perform various calculations based on simple mathematical concepts.

2. Example of Euler Problem – Problem 1: Find the sum of all natural numbers from 1 to 1000 that are multiples of 3 or 5

To clearly understand the problem, let’s restate it.
We want to find the numbers from 1 to 1000 that are divisible by 3 or 5 and calculate their sum.

3. Problem-solving Approach

This problem can be solved using simple loops and conditional statements.
The following approach can be considered.

  1. Iterate through all natural numbers from 1 to 1000.
  2. Check if each number is divisible by 3 or 5.
  3. Sum the numbers that meet the criteria.
  4. Print the final result.

4. Implementing in Kotlin

Now, let’s solve the problem with Kotlin code according to the above approach.

fun main() {
        var sum = 0
        for (i in 1 until 1000) {
            if (i % 3 == 0 || i % 5 == 0) {
                sum += i
            }
        }
        println("The sum of natural numbers from 1 to 1000 that are multiples of 3 or 5 is: $sum")
    }

4.1 Explanation of the Code

The above code is structured as follows:

  • var sum = 0: Initializes a variable to store the sum.
  • for (i in 1 until 1000): Iterates from 1 to 999. The until keyword is used so that 1000 is not included.
  • if (i % 3 == 0 || i % 5 == 0): Checks if the current number is a multiple of 3 or 5.
  • sum += i: Adds the current number to the sum if it meets the condition.
  • println(...): Prints the final result.

5. Execution Result

When the program is run, you can obtain the following result:


    The sum of natural numbers from 1 to 1000 that are multiples of 3 or 5 is: 233168
    

6. Additional Lessons Learned

Through this problem, we can learn a few important points:

  • Step-by-step thought process for problem-solving.
  • Effective use of conditional statements and loops.
  • How to output results.

7. Extension of the Problem

This problem can be extended in several different ways. For example, you can change 1000 to 10000 or try using different numbers other than 3 and 5. Changing the scope of the problem can also provide more practice.

8. Conclusion

In this article, we explored how to solve the Euler problem using Kotlin. Algorithmic problems are great practice for improving various problem-solving skills. I hope you continue to solve various problems and gain experience.

9. References