top1编程
← 返回题目
题解

【基础】连续数的和

3 条题解

  • 0
    @ 2026-7-29 20:23:37
    #include <bits/stdc++.h>
    using namespace std;
    int a[100005];
    int main(){
    	int n, k, c = 0;
    	cin >> n >> k;
    	for (int i = 1; i <= n; i++) {
    		a[i] = a[i - 1] + i;
    	}
    	for (int i = k; i <= n; i++) {
    		int temp = a[i] - a[i - k];
    		if (sqrt(temp) == (int)sqrt(temp)) {
    			c++;
    		}
    	}
    	cout << c;
    	return 0;
    }
    
    • 0
      @ 2026-7-29 0:06:22
      #include <bits/stdc++.h>
      using namespace std;
      int a[100005];
      int main(){
      	int n, k, c = 0;
      	cin >> n >> k;
      	for (int i = 1; i <= n; i++) {
      		a[i] = a[i - 1] + i;
      	}
      	for (int i = k; i <= n; i++) {
      		int temp = a[i] - a[i - k];
      		if (sqrt(temp) == (int)sqrt(temp)) {
      			c++;
      		}
      	}
      	cout << c;
      	return 0;
      }
      
      • 0
        @ 2026-7-28 22:09:35
        #include<bits/stdc++.h>
        using namespace std;
        long long a[70005];
        int main(){
            long long s=0;
            long long n,k;
        	cin>>n>>k;
        	for(int i=1;i<=n;i++){
        		a[i]=a[i-1]+i;//构建前缀和
        	}
        	for(int i=k;i<=n;i++){//循环k范围的最后一个位置
        		int x=a[i]-a[i-k];//找到k区间内的和
                if(sqrt(x)==(int)sqrt(x)){//区间和是完全平方数
        	    	s++;
        	    } 
        	}
        	cout<<s;
        }
        
        • 1