top1编程
← 返回题目
题解

【入门】将n拆成3个数的和

2 条题解

  • 0
    @ 2026-7-29 20:24:23
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
    	int n, a, b, c;
    	cin >> n;
    	for (a = 1; a <= n / 3; a++) {  //需要遵循a<=b<=c的原则才可以保证不重复。
    		for (b = a; b <= (n - a) / 2; b++) {
    			c = n - a - b;
    			if (b <= c) {
    				cout << n << "=" <<  a << "+" << b << "+" << c << endl;
    			}
    		}
    	}
    	return 0;
    }
    
    • 0
      @ 2026-7-29 0:15:24
      #include <bits/stdc++.h>
      using namespace std;
      int main(){
      	int n;
      	cin>>n;
      	// 三个数 平分
      	for(int i=1;i<=n/3;i++){
      		// 剩下2个数 再平分
      		// 后面的数字大于前面的数字 防止出现重复的地方
      		for(int j=i;j<=(n-i)/2;j++){
      			// 第三个数字用n减去第一个和第二个数字就可以
      			cout<<n<<"="<<i<<"+"<<j<<"+"<<(n-i-j)<<endl;
      		}
      	}
      	return 0;
      }
      
      • 1