Problem Description
Autumn arrived, n monkeys picked a lot of apples put into the cave, the second balance of the contract. These monkeys adore Monkey King monkey, so all want to leave him some apples. The first monkey crept into the cave, divided the apples evenly into n parts, ate the remaining m apples, hid them, and finally put the remaining apples together again. The monkeys quietly came to the cave, all doing the same operation, just about every time there are a few m apples. The next day, the monkeys came to the cave, the rest of the apples into the n points, the coincidence, or the remaining m. Ask, how many apples did these monkeys pick up at least.
Input Format
Two integers, N m
output Format
An integer that represents the number of original apples
Sample Input
5 1
Sample Output
15621
data size and conventions
0<m<n<9
Analysis Ideas
1. Forward thinking
The monkey is n, the remaining m apples each time. The apples are at least n+m, and the apples increase by n at a time. Such as:
n = 5, M = 1. The Apple is at least 6, and its possible values are 6, 11, 16, 21, 26 .....
This can be started from the minimum number of apples to increment, each monkey to the Apple operation once, the operation is:
Number of apples/monkeys-remainder. If the number of apples is no more than M after a monkey's split operation, this non-demand Apple number will continue to increase the next possible number of apples. Until satisfied then jump out of the loop, and then determine whether this number is still more than 1, is the correct answer, output.
2. Recursive thinking
You can also think back and forth, apples and monkeys are the same number of apples at least. The apples were divided n+1 times, ate n times, and finally left M.
Thus, the formula can be obtained:
Total Apples = n ^ (n + 1)-n * m + M
Implementation Code
//1. 正向思维#include <iostream>int main(){ int n, m; std::cin >> n >> m; for(int j = n + m; ; j += n) { int i, sum = j; for(i = 0; i < n; ++i) { if(sum % n != m) break; sum = sum - sum/n - m; } if(i == n && sum % n == m) { std::cout << j; break; } } return 0;}
//2.递推思维#include <iostream>#include <cmath>int main() { int n, m; std::cin >> n >> m; std::cout << pow(n, n+1) - n * m + m << std::endl; return 0;}
The monkeys divide the apples