Two applications cumulative counting method: Knights of coins and playing cards magic

Knight's gold

The king gold as wages paid to loyal knight. The first day, Knight received a gold coin; two days (days two and three) years, received two gold coins every day; three days later (fourth, five or six days), the received three daily gold coins; four days later (seventh, eight, nine, ten) years, received four gold ...... this day payroll mode will always continue like this: when N N consecutive days to receive gold coins every day, Knights N + 1 consecutive days after, the coins received N + 1 (N is any positive integer) every day. You need to write a program to determine from the first day of a given number of days, the Knights won a total of how many gold coins.
Input format
an integer (range of 1 to 10000), the number of days.
Output Format
gold coins Knight obtained.
Input Sample
6
Sample Output
14

#include<iostream>
using namespace std;
int main()
{
	int n;
	while (cin >> n){
		int money = 1, day = 1, sum = 0;//当前的金币数money、来了第day天了、累积钱数sum
		for (int i = 1; i <= n; i++){
			sum += money;
			if (i == day){
				money++;
				day += money;
			}
		}
		cout << sum << endl;
	}
}

Such as input six days, day += money;the day is divided into n intervals 1, 2, three gold, i == day represents a gold wages has entered the next interval.

Magic playing cards

A stack of cards hanging on the table, if a card, you can add up to half of it hung on the table. If two cards, the top goes out of a maximum of half below that card, and that card out of the bottom of the desktop up to one-third. Therefore, two cards hanging on the desktop total length 1 / 2 + 1 / 3 = 5 / 6 1/2+1/3=5/6 , generally, the n-card desktop projecting length of 1/2 + 1/3 +the top piece of the lower projecting plate 1/2 card, the second block piece of card which extends in the third card, and so on, and finally extending the desktop that card 1 / (n + 1).
Input: a set of test cases, to two decimal floating-point type, it indicates the total length of the required suspension of the table.
Output: a set of test cases correspond to one output, requires a minimum number of cards.
Sample input:
1.00
3.71
0.04
5.19
Output:
. 3
61 is
. 1
273

#include<iostream>
using namespace std;
int main()
{
	double len;
	while (cin >> len){
		double sum = 0;
		int n = 0;
		while (sum < len){
			n++;
			sum += 1.0 / (n + 1);
		}
		cout << n << endl;
	}
}

Note: The current sum <len time, then n ++, n 0 is the initial value, and then add a new sum to the increased length.

n++;sum += 1.0 / (n + 1);

If the initial value n 1, the above-described two reversed order of the code, such that the end result will be one greater than the true value.

Guess you like

Origin blog.csdn.net/Vickers_xiaowei/article/details/90520622