? How can I get a negative number after running?
The king gave his loyal knights gold coins as wages. On the first day, the knight received a gold coin; On the following two days(the second and third days), you receive two gold coins per day; For the next three days(the fourth, fifth, and sixth days), they received three gold coins per day; For the next four days(seventh, eighth, ninth, tenth), you receive four gold coins a day... ; This pattern continues: after receiving N coins per day for N days, the knight will receive N+1 coins per day for N+1 days.
Calculate how much gold the knight received in the previous K days.
Input
Enter only one line containing a positive integer K, representing the number of days in which gold coins are issued.
Output
The output is only 1 line and contains a positive integer, the number of coins the knight received.
Example input
6
Example output
14
Prompt
The knight receives a gold coin on the first day; On the second and third days, I received two gold pieces each day; On the fourth, fifth and sixth days, three gold coins were received each day. So I get 1+2+2+3+3+3=14 gold pieces.
[Data Description]
For 100% data, 1 ≤ K ≤ 10,000.
Source
NOIP2015 popularization group
has the code, the answer is wrong, 80%, please answer
#include<bits/stdc++.h>
using namespace std;
int a[3][2];
int main() {
int n,sum=0,k,k_2;
cin >> n;
for(int i=1;;i++){
int sum_2=sum;
sum+=i*i;
if(sum>n || sum==n)
{
k=i;
k_2=sum_2;
break;
}
}
//cout<<sum<<endl<<k<<endl<<k_2;
cout<<sum+(n-k_2-1)*(k+1);
return 0;
}
0 Answer
code modified
the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > the code idea is calculated according to the gold distribution regularity of the title, but there are some problems.
First, when calculating the number of gold coins obtained every day for i days, the code uses i * i, which is wrong. It should be calculated according to the problem rule, that is, when the knight receives N gold coins every day for N consecutive days, he will receive N+1 gold coins every day for N+1 consecutive days. So you should use i < = k ? i: k + 1.
Second, the variable a in the code is not used and can be removed.
Finally, sum < can be used to judge the boundary conditions; = n to see if it exceeds the number of gold coins issued in the previous K days.
Below is the modified code, can AC this problem.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int k = scanner.nextInt();
int coins = 0;
int days = 0;
int n = 1;
while (days < k) {
for (int i = 0; i < n && days < k; i++) {
coins += n;
days++;
}
n++;
}
System.out.println(coins);
}
}
这家伙很懒,什么都没留下...