그래서 파이썬과 자바에서 이미 해결 한 문제가 있습니다.Java와 Python 구현의 속도
파이썬 : 문제는 모든 고유 번호를 찾을 수 8000 개 * 8000 개 요소의 곱셈 테이블입니다
table = 8000
unique_prods = []
start = 1
for i in range(table*table + 1):
unique_prods.append(0)
for x in range(1, table + 1):
for y in range(start, table + 1):
# print '{:4}'.format(x * y),
if not unique_prods[x * y] == x * y:
unique_prods[x * y] = x * y
start += 1
# print
# print unique_prods
print len(unique_prods)
자바 : 나는 놀라운 것을 발견
public class Test {
public static void main(String[] args) {
int table = 8000;
int [] myArray = new int[table*table + 1];
int count = 1;
for (int i = 0; i < table*table + 1; i++) {
myArray[i] = 0;
}
for (int x = 1; x < table + 1; x++) {
for (int y = count; y < table + 1; y++) {
if (! (myArray[x * y] == x * y)) {
myArray[x * y] = x * y;
}
}
count += 1;
// System.out.println(count);
}
count = 0;
for (int i = 0; i < table*table + 1; i++) {
if(myArray[i] != 0) {
count += 1;
}
}
System.out.println(count);
}
}
자바 구현 잠깐, 파이썬 버전은 1 분 이상 걸렸다. 파이썬 성능을 향상시켜 Java 구현 속도에 더 가깝게 할 수있는 방법이 있습니까?
아, 이제 파이썬이 잘못된 대답을 내뱉는 것을 보았습니다. 그러나 목록을 반복하여 쉽게 수정할 수 있습니다. 미안합니다. –
'myArray [x * y]가'x * y'와 동일하게 설정되기 전에'x * y'와 같지 않은지 확인하는 이유는 무엇입니까? 이미 같으면 자체와 동일하게 설정해도 값이 변경되지 않습니다. 이미 같지 않으면'x * y'로 설정됩니다. ''if''는 불필요합니다. – curiousinternals
'unique_prods.append (0)'은 내 컴퓨터에서 15 배 빠른 unique_prods = [0] * (table * table + 1)로 바꿔야합니다. – PeterE