programming-challenges (2/3/4)-D Sqr/Rects/Cubes/Boxes ? (111206) 题解

这道题难度设成2好像太高了,其实很容易找到规律的。只是要注意数据类型用long long,保证数据不会溢出。

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <assert.h>
#include <algorithm>
#include <math.h>
#include <ctime>
#include <functional>
#include <string.h>
#include <stdio.h>
#include <numeric>
#include <float.h>

using namespace std;

long long tr2(long long n) {
	long long result = 0; 

	for (long long i = n; i >= 1; i--) {
		for (long long j = n; j >= 1; j--) {
			if (i == j) continue;
			result += i * j; 
		}
	}

	return result;
}

long long tr3(long long n) {
	long long result = 0;

	for (long long i = n; i >= 1; i--) {
		for (long long j = n; j >= 1; j--) {
			for (long long k = n; k >= 1; k--) {
				if (i == j && j == k) continue;
				result += i * j * k;
			}
		}
	}

	return result;
}

long long tr4(long long n) {
	long long result = 0;

	for (long long i = n; i >= 1; i--) {
		for (long long j = n; j >= 1; j--) {
			for (long long k = n; k >= 1; k--) {
				for (long long l = n; l >= 1; l--) {
					if (i == j && k == l && i == k) continue;
					result += i * j * k * l;
				}
			}
		}
	}

	return result;
}

long long sq2(long long n) {
	long long result = 0; 

	for (long long i = n; i >= 1; i--) {
		result += i * i; 
	}

	return result;
}

long long sq3(long long n) {
	long long result = 0; 

	for (long long i = n; i >= 1; i--) {
		result += i * i * i; 
	}
	
	return result; 
}

long long sq4(long long n) {
	long long result = 0;

	for (long long i = n; i >= 1; i--) {
		result += i * i * i * i;
	}

	return result;
}

int main() {
	int n = 0; 

	while (cin >> n) {
		cout << sq2(n) << " " << tr2(n) << " "
			<< sq3(n) << " " << tr3(n) << " "
			<< sq4(n) << " " << tr4(n) << endl;
	}

	return 0; 
}


你可能感兴趣的:(Algorithm,C++)