일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 큰수의법칙
- 블록코딩
- 상합
- 확률실험
- 구분구적법
- 리만합
- project euler
- 재귀함수
- 알지오매스
- counting sunday
- java
- 프로젝트 오일러
- Geogebra
- 프랙탈
- 작도
- python
- 피타고라스 정리
- 이항분포
- 지오지브라
- 수학탐구
- 파이썬
- 정오각형
- algeomath
- 제곱근의뜻
- 큰 수의 법칙
- 하합
- 삼각함수의그래프
- 몬테카를로
- 오일러
- 시뮬레이션
- Today
- Total
이경수 선생님의 수학실험실
Problem 14(Longest Collatz sequence) 본문
Problem 14(Longest Collatz sequence)
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
In Python:
#PE14 Longest Collatz sequence
import time
start_time = time.time()
lenChain=[]
for num in range(2, pow(10, 6)):
i = 0
while num > 1:
i += 1
if num % 2 == 0:
num /= 2
else:
num = 3 * num + 1
lenChain.append(i)
print(lenChain.index(max(lenChain))+2)
print(time.time() - start_time, "seconds")
Run Time: 44.05256390571594 seconds
In Java:
//Euler14 Longest Collatz sequence
package project_euler;
public class Euler14 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
int count = 0;
int maxCount = 0;
int maxValue = 0;
long num = 0;
for (int i = 2; i < Math.pow(10, 6); i++) {
num = i;
count = 0;
while (num > 1) {
if (num % 2 == 0) {
num /= 2;
}
else {
num = 3 * num + 1;
}
count++;
}
if (count > maxCount) {
maxCount = count;
maxValue = i;
}
}
System.out.println(maxValue);
long endTime = System.currentTimeMillis();
System.out.println((double)(endTime - startTime)/(double)1000 + "seconds");
}
}
Run time: 0.459seconds
Solution: 837799
[from Project Euler: https://projecteuler.net/problem=14]
'Project Euler' 카테고리의 다른 글
problem16 (Power digit sum) (0) | 2019.02.14 |
---|---|
Problem 15(Lattice paths) (0) | 2019.02.11 |
Problem 13(Large sum) (0) | 2019.02.10 |
Problem 12(Highly divisible triangular number) (0) | 2019.02.10 |
Problem 11(Largest product in a grid) (0) | 2019.02.10 |