The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
출처: https://projecteuler.net/
1부터 n까지의 자연수를 차례로 더하여 구해진 값을 triangle number 이라할 때 500개 이상의 약수를 갖는 가장 작은 triangle number 을 구하는 문제입니다.
루트값의 divisors 갯수를 구한 후 2를 곱하는 방법으로 시간 복잡도를 줄였고 1~n 의 합은 n(n+1)/2로 구했습니다.
my solving
c++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | #include <iostream> #include <fstream> #include <algorithm> using namespace std; typedef long long ll; int getNumDivisors(ll num) { int ret = 0; ll sqrtn = sqrt(num); for (ll i = 1; i <= sqrtn; i++) { if (num % i == 0) ret++; } if (num > 1) ret *= 2; return ret; } int main() { ll ret = 0; for (ll i = 1; ; i++) { int triangle = i * (i + 1) / 2; if (getNumDivisors(triangle) >= 500) { ret = triangle; break; } } cout << ret << endl; system("pause"); return 0; } | cs |
'Algorithm, Data structure > Solved Algorithmic Problem' 카테고리의 다른 글
Project Euler #14 - Longest Collatz sequence (0) | 2016.06.16 |
---|---|
Project Euler #13 - Large sum (0) | 2016.06.16 |
Project Euler #11 - Largest product in a grid (0) | 2016.06.12 |
Project Euler #10 - Summation of primes (0) | 2016.06.12 |
Project Euler #9 - Special Pythagorean triplet (0) | 2016.06.12 |