Project_Euler-45 题解
题目
思路
非常简单,枚举六边形数字,然后判断他们是不是三角形和五边形数,如果是,那么输出。
代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
typedef long long ll;
ll triangle(ll n) {
return (n * (n + 1)) >> 1;
}
ll pentagonal(ll n) {
return (n * (3 * n - 1)) >> 1;
}
ll hexagonal(ll n) {
return n * (2 * n - 1);
}
ll is_triangle(ll n) {
printf("is_triangle: %lld...\n", n);
ll head = 1, tail = n, mid;
while (head <= tail) {
mid = (head + tail) >> 1;
if (triangle(mid) == n) return 1;
if (triangle(mid) < n) head = mid + 1;
else tail = mid - 1;
}
printf("is_triangle: %lld is not a triangle.\n", n);
return 0;
}
ll is_pentagonal(ll n) {
printf("is_pentagonal: %lld...\n", n);
ll head = 1, tail = n, mid;
while (head <= tail) {
mid = (head + tail) >> 1;
if (pentagonal(mid) == n) return 1;
if (pentagonal(mid) < n) head = mid + 1;
else tail = mid - 1;
}
printf("is_pentagonal: %lld is not a pentagonal.\n", n);
return 0;
}
ll main() {
ll num = 0;
for (ll i = 2; num < 2; i++) {
ll tar = hexagonal(i);
if (!is_pentagonal(tar)) continue;
if (!is_triangle(tar)) continue;
num++;
printf("%lldth = %lld\n", num, tar);
}
return 0;
}
优化思路
发现六边形数字一定是三角形数字,因此枚举六边形数字的画就不需要再判断三角形数字了。
优化代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
typedef long long ll;
ll pentagonal(ll n) {
return (n * (3 * n - 1)) >> 1;
}
ll hexagonal(ll n) {
return n * (2 * n - 1);
}
ll is_pentagonal(ll n) {
printf("is_pentagonal: %lld...\n", n);
ll head = 1, tail = n, mid;
while (head <= tail) {
mid = (head + tail) >> 1;
if (pentagonal(mid) == n) return 1;
if (pentagonal(mid) < n) head = mid + 1;
else tail = mid - 1;
}
printf("is_pentagonal: %lld is not a pentagonal.\n", n);
return 0;
}
ll main() {
ll num = 0;
for (ll i = 2; num < 2; i++) {
ll tar = hexagonal(i);
if (!is_pentagonal(tar)) continue;
num++;
printf("%lldth = %lld\n", num, tar);
}
return 0;
}