Skip to content

Instantly share code, notes, and snippets.

@Hikari9
Created December 14, 2015 01:32
Show Gist options
  • Save Hikari9/38f9de8fb93e7028bb94 to your computer and use it in GitHub Desktop.
Save Hikari9/38f9de8fb93e7028bb94 to your computer and use it in GitHub Desktop.
Count all possible triangles with distinct lengths <= n
#include <iostream>
#include <cstdio>
using namespace std;
int sumsquare(int n) {
return n * (n + 1) / 2 * (2 * n + 1) / 3;
}
int range(int n) {
return n * (n + 1) / 2;
}
int main() {
int n;
while (cin >> n) {
int n2 = n / 2, n1 = n - n2 - 1;
int c = 0;
for (int i = 1; i <= n; ++i) {
for (int j = i + 1; j <= n; ++j) {
for (int k = j + 1; k <= n; ++k) {
if (i + j > k)
c++;
}
}
}
cout << c << endl;
c = 0;
for (int i = 1; i <= n / 2; ++i) {
// c += max(0, (i - 1) * (n - 2 * i - 1));
int occ = min(i, n - i);
c += max(0, n - 2*i) * (i - 1);
c += occ * occ - occ * (occ + 1) / 2;
}
// cout << '\t' << c << endl;
for (int i = n / 2 + 1; i <= n; ++i) {
// c += max(0, (i - 1) * (n - 2 * i - 1));
int occ = min(i, n - i);
c += max(0, n - 2*i) * (i - 1);
c += occ * occ - occ * (occ + 1) / 2;
}
cout << c << endl;
c = 0;
for (int i = 1; i <= n / 2; ++i) {
// c += (n - 2 * i) * (i - 1) + i * i - i * (i + 1) / 2;
// c += n * i - 2 * i * i + 2 * i - n + i * i - i * (i + 1) / 2;
c += (n + 2) * i - n - i * i - i * (i + 1) / 2;
}
// cout << '\t' << c << endl;
for (int i = n / 2 + 1; i <= n; ++i)
c += (n - i) * (n - i) - (n - i) * (n - i + 1) / 2;
cout << c << endl;
c = 0;
c += (n + 2) * range(n2) - n*n2 - sumsquare(n2) - (sumsquare(n2) + range(n2)) / 2;
// cout << '\t' << c << endl;
for (int i = n / 2 + 1; i <= n; ++i)
c += (n - i) * (n - i) - (n - i) * (n - i + 1) / 2;
cout << c << endl;
c = 0;
c += (n + 2) * range(n2) - n*n2 - sumsquare(n2) - (sumsquare(n2) + range(n2)) / 2;
c += sumsquare(n1) - (sumsquare(n1) + range(n1)) / 2;
cout << c << endl;
c = 0;
if (n & 1) {
int r = range(n / 2);
int s = sumsquare(n / 2);
c += (n + 2) * r - n * n1 - s - (s + r) / 2 + s - (s + r) / 2;
} else {
// n1 == n2 - 1
int r = range(n / 2);
int s = sumsquare(n / 2);
c += (n + 2) * r - n * n2 - s - (s + r)/2;
c += s - n2 * n2 - (s - n2 * n2 + r - n2)/2;
// c += (n + 2) * range(n2) - n*n2 - sumsquare(n2) - (sumsquare(n2) + range(n2)) / 2;
// c += sumsquare(n1) - (sumsquare(n1) + range(n1)) / 2;
}
cout << c << endl;
/// FINAL FORMULA
int r = range(n / 2);
int s = sumsquare(n / 2);
c = (n + 1) * r - n / 2 * n - s;
if (n % 2 == 0) c -= range(n/2 - 1);
cout << c << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment