内容中心

2026年质量好的找工作本地招聘排行榜-浙江环讯人力资源有限公司

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

  1. Read Input: First, we read the input list of integers.
  2. Find Maximum Value: Determine the maximum value in the input list to know the upper limit for generating triangular numbers.
  3. 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.
  4. 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

  1. Reading Input: The input is split into a list of integers using map(int, input().split()).
  2. Max Value: The maximum value in the input list is found using max(input_nums).
  3. Generating Triangular Numbers: We initialize current to 0 and step to 1. For each iteration, we add step to current to get the next triangular number. If this number exceeds the maximum value, we stop. Otherwise, we add it to our result list and increment step by 1 (since the next triangular number is the sum of the current one plus the next natural number).
  4. 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.

浙江环讯人力资源有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?