萌新代码求优化

P2669 [NOIP2015 普及组] 金币

yuqirui @ 2022-04-02 21:24:53

 #include<bits/stdc++.h>
    using namespace std;
    int main()
    {
      int k,h=0,p=0;
      cin>>k;
      for(int i=1;;i++)
      {
        for(int j=1;j<=i;j++)
        {
            if(p>=k)  
            {
                cout<<h;
                return 0;
              }
            else
            {
                h+=i,p++;
            }

          }

      }

      return 0;
    }

by WA_AW @ 2022-04-02 21:27:08

一层循环就好啊


by WA_AW @ 2022-04-02 21:29:34

你没加注释,所以我也没加,自行理解吧

    int date;
    int d=1,s=0;
    int i,p=1;
    cin>>date;
    for(i=1; i<=date; i++)
    {
        s+=d;
        if(i==p)
        {
            d++;
            p+=d;
        }
    }
    cout<<s<<endl;
    return 0;

by WA_AW @ 2022-04-02 21:30:01

@yuqirui


by yuqirui @ 2022-04-02 21:30:49


懂了懂了

by MT_Shang @ 2022-04-09 17:22:15

更简洁代码

#include<bits/stdc++.h>
using namespace std;
int main(){
    long long k,s=0,t=1; 
    scanf("%ld",&k);
    while(k>=t){
        s=s+t*t;
        k=k-t;
        t++;
    }
    s=s+k*t;
    printf("%ld",s);
    return 0;
}

by BBD_XBC @ 2022-04-14 18:26:51

萌新代码如下

#include<iostream>
using namespace std;
int main()
{
    int k,i,js=0;
    cin>>k; 
    for(i=1;;i++)
    {
        js=js+i*i;
        if((1+i)*i/2>=k)
        {   
            js=js-i*i+(k-i*(i-1)/2)*i;
            break;
        }
    }
    cout<<js;
    return 0;
}

看一看能不能理解。


by lizhehao @ 2022-10-07 12:47:08

看一看啊。(萌新解法)

#include<iostream>
using namespace std;
void haha(int times){
    int sum=0,a=1,i=1;
        for(i=1;i<=times;i++){
        times-=i;
        sum+=a*a;
        a++;
    }   
    cout<<sum+times*a;
}
int main(){
    int times,sum=0,a=1,i=1;
    cin>>times;
    haha(times);
    return 0;
}

注:这真的是萌新解法


|