During research dedicated to the emergence of life on the planet Olympia, scientists…
- User
During research dedicated to the emergence of life on the planet Olympia, scientists made several sensational discoveries:
All living organisms on the planet originated from a single bacterium Bitozoria Programulis.
Evolution proceeded step by step (according to scientists' hypothesis—during climate changes on the planet).
At each step of evolution, exactly two subspecies formed from each species, and the previous species disappeared.
If the appearance of the bacterium Bitozoria Programulis is considered the first step of evolution, then the currently existing living organisms are at the n-th step.
To avoid creating names during the research, scientists numbered all the species of organisms that ever existed on the planet. To do this, they drew an evolutionary tree with the root Bitozoria Programulis, which was assigned the number 1. Then, they numbered the species of each evolutionary step from left to right. Thus, the direct subspecies of Bitozoria Programulis were assigned the numbers 2 and 3. Next, the species of the third step of evolution were numbered—the subspecies of species 2 received the numbers 4 and 5, and those of species 3 received the numbers 6 and 7, and so on.
Write a program that, given the numbers of two species, calculates the number of their closest common ancestor in the evolutionary tree.
Input The first line contains the number of evolutionary stages n (1≤n≤100) that have occurred on the planet Olympia up to the present time. The second and third lines each contain a natural number representing the species numbers for which the closest common ancestor's number needs to be found.
Output Output one natural number—the number of the closest ancestor for the two species.
Examples Input #1 4 15 12 Answer #1 3 Input #2 18 233016 233008 Answer #2 14563
- Assistant
Certainly! Here's a Python program that, given the numbers of two species, calculates the number of their closest common ancestor in the evolutionary tree described:
python# Read the number of evolutionary stages n = int(input()) # Read the species numbers u = int(input()) v = int(input()) # Find the lowest common ancestor while u != v: if u > v: u = u // 2 else: v = v // 2 # Output the number of the closest common ancestor print(u)Explanation:
- The evolutionary tree is a complete binary tree where each node's parent is the node with the number equal to the floor of the node's number divided by 2.
- To find the lowest common ancestor (LCA) of two nodes in such a tree:
- While the two nodes are not the same, move the node with the higher number up to its parent by dividing its number by 2 (using integer division).