이경수 선생님의 수학실험실

Problem 12(Highly divisible triangular number) 본문

Project Euler

Problem 12(Highly divisible triangular number)

(이경수) 2019. 2. 10. 16:00

Problem 12(Highly divisible triangular number)

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?



In Python:

#PE12 Highly divisible triangular number
import time


def divcount(n):
result = 1
for i in range(2, int(n / 2) + 1):
count = 0
while n % i == 0:
n /= i
count += 1
result *= (count + 1)
if n == 1:
break
if result == 1:
return 2
else:
return result


start_time = time.time()
triangular = 1
i = 2

while divcount(triangular) < 500:
triangular = triangular + i
i += 1
print(triangular)
print(time.time() - start_time, "seconds")

Run time: 5.669299840927124 seconds



In Python:


//Euler12 Highly divisible triangular number

package project_euler;


public class Euler12 {

public static int divCount(long n) {

int count = 0;

int result = 1;

long num = n;

for (int i = 2; i < Math.ceil(n / 2) + 1; i++) {

count  = 0;

while (num % i == 0) {

num /= i;

count++;

}

result *= count + 1;

if (num == 1) break;

}

if (result == 1) {

return 2;

}

else {

return result;

}

}

public static void main(String[] args) {

long startTime = System.currentTimeMillis();

long triangular = 1;

int i = 2;

while (divCount(triangular) < 500) {

triangular += i;

i++;

}

System.out.println(triangular);

long endTime = System.currentTimeMillis();

System.out.println((double)(endTime - startTime)/(double)1000 + "seconds");

}

}


Run time0.36seconds



Solution: 76576500


[from Project Euler: https://projecteuler.net/problem=12]








'Project Euler' 카테고리의 다른 글

Problem 14(Longest Collatz sequence)  (0) 2019.02.10
Problem 13(Large sum)  (0) 2019.02.10
Problem 11(Largest product in a grid)  (0) 2019.02.10
Problem 10(Summation of primes)  (0) 2019.02.09
Problem 9(Special Pythagorean triplet)  (0) 2019.02.09
Comments