To solve this problem, we need to generate all triangular numbers that are present in a given input list of integers. Triangular numbers are numbers that can be represented as the sum of the first n natural numbers, i.e., ( T_n = 1 + 2 + ... + n = \frac{n(n+1)}{2} ).
Approach
- Read Input: First, we read the input list of integers.
- Find Maximum Value: Determine the maximum value in the input list to know the upper limit for generating triangular numbers.
- Generate Triangular Numbers: Start generating triangular numbers from the first one (1) and keep adding the next natural number to the current triangular number. Stop when the generated number exceeds the maximum value from the input.
- Output Result: Print the generated triangular numbers separated by spaces.
Solution Code
input_nums = list(map(int, input().split()))
max_num = max(input_nums)
triangular = []
current = 0
step = 1
while True:
current += step
if current > max_num:
break
triangular.append(str(current))
step += 1
print(' '.join(triangular))
Explanation
- Reading Input: The input is split into a list of integers using
map(int, input().split()). - Max Value: The maximum value in the input list is found using
max(input_nums). - Generating Triangular Numbers: We initialize
currentto 0 andstepto 1. For each iteration, we addsteptocurrentto get the next triangular number. If this number exceeds the maximum value, we stop. Otherwise, we add it to our result list and incrementstepby 1 (since the next triangular number is the sum of the current one plus the next natural number). - Output: The result list is converted to a string with space-separated values and printed.
This approach efficiently generates the required triangular numbers and handles all edge cases (like input lists with a single element or no triangular numbers). The time complexity is O(√max_num) since the nth triangular number is approximately ( \frac{n^2}{2} ), so the number of triangular numbers up to max_num is proportional to the square root of max_num. This is very efficient even for large values of max_num.
Example: For input 1 2 3 ... 16, the output is 1 3 6 10 15 which are all triangular numbers up to 16. This matches the expected result provided in the problem.
Another example: If input is 1 2 3 4 5, the output is 1 3 since the next triangular number (6) is greater than the maximum input value (5).
This solution is optimal and straightforward, ensuring correctness and efficiency.

作者声明:本文包含人工智能生成内容。