web123456

The gold coin issue (The king paid gold coins as wages to loyal knights.)

Title Description
The king gave gold coins as wages to loyal knights. On the first day, the knight receives one gold coin; on the following two days (the second and third days), he receives two gold coins per day; on the following three days (the fourth, fifth, and sixth days), he receives three gold coins per day; and on the following four days (the seventh, eighth, ninth, and tenth days), he receives four gold coins per day. ......; this pattern of payroll will continue in this way: after N gold coins are received per day for N consecutive days, the knight will receive N+1 gold coins per day for the following N+1 consecutive days.

Calculate how many gold coins the knight has earned in total during the first K days.
importation
The input has only 1 line and contains a positive integer K (1 ≤ K ≤ 10000) indicating the number of days for which gold coins will be issued.
exports
The output is only 1 line and contains a positive integer, the number of gold coins received by the knight.
Sample Input
6
Sample Output
14
draw attention to sth.
The knight receives one gold coin on the first day; two gold coins per day on the second and third days; and three gold coins per day on the fourth, fifth and sixth days. Therefore, the total number of coins received is 1+2+2+3+3+3=14 coins.
[Analysis]
It is easier to think of a solution when the number of gold coins collected by the knight is written in the following form
The number of gold coins received in the previous 10 days (including the 10th day), for example, would be the number of gold coins received:
1 (first day)
2 2 (second and third days)
3 3 3 3 (days 4, 5, 6)
4 4 4 4 4 (days 7, 8, 9, 10)
If you want to print this numeric triangle above, you only need two for loops:

for(int i=1;i<=4;i++){
		for(int j=1;j<=i;j++){
			cout<<i<<" ";
		}
		cout<<endl;
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Analogous to this code, the inner for loop can represent the number of days, then just modify the loop termination condition to terminate the loop when the number of days == k.
The solution code for this problem is as follows:

#include<iostream>
using namespace std;
int main(){
	int k,day=0,sum=0;
	cin>>k;
	for(int i=1;;i++){
		for(int j=1;j<=i;j++){
			day++;
			sum+=i;
			if(day==k){// When the number of days is equal to the given number of days, output the total number of gold coins and terminate the program
				cout<<sum;
				return 0;
			}
		} 
	}
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17