projecteuler---->problem:2

题目:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

翻译:

Fibonacci数列的每后一项都是前面两项的和,若开始的头两项是1和2,那么前10个项就是:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

请求出以上Fibonacci数列中不超过400,0000的所有偶数的和。

解答:

sum,a,b,c=2,1,2,3
while(1):
	c=a+b
	a = b
	b = c
	if c > 4000000:
		break
	if c % 2 == 0:
		 sum += c
print sum
	


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
To solve this problem, we can follow the following steps: 1. Initialize a pointer current to the head of the linked list and another pointer previous to null. 2. Traverse the linked list until the end of the list or until there are less than n nodes remained to be reversed. 3. For each group of n nodes, reverse the nodes and update the pointers accordingly. 4. If there are less than n nodes remaining, reverse them as well. 5. Return the updated head of the linked list. Here is the Python code that implements the above algorithm: ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def reverseLinkedList(head, n): current = head previous = None while current: last_node_of_previous_part = previous last_node_of_sub_list = current i = 0 while current and i < n: next_node = current.next current.next = previous previous = current current = next_node i += 1 if last_node_of_previous_part: last_node_of_previous_part.next = previous else: head = previous last_node_of_sub_list.next = current previous = last_node_of_sub_list return head ``` Here is an example usage of the above function: ```python # create input linked list: A -> B -> C -> D -> E -> F -> G -> H -> I a = ListNode("A") b = ListNode("B") c = ListNode("C") d = ListNode("D") e = ListNode("E") f = ListNode("F") g = ListNode("G") h = ListNode("H") i = ListNode("I") a.next = b b.next = c c.next = d d.next = e e.next = f f.next = g g.next = h h.next = i # reverse the linked list in groups of 3 nodes head = reverseLinkedList(a, 3) # print the updated linked list: A -> D -> C -> B -> G -> F -> E -> I -> H current = head while current: print(current.val, end=" -> ") current = current.next print("None") ``` Output: ``` A -> D -> C -> B -> G -> F -> E -> I -> H -> None ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值