如果 a+b+c=1000,且 a^2+b^2=c^2(a,b,c 為自然數),如何求出所有a、b、c可能的組合?Java/JavaScript/C/Python耗時對比


 

如果 a+b+c=1000,且 a^2+b^2=c^2(a,b,c 為自然數),如何求出所有a、b、c可能的組合?

不考慮算法優化,十億次循環計算判斷 Java/JavaScript/C/Python 多次測試耗時對比。

 

Java

單次總耗時957毫秒

import java.util.Date;


public class algorithm {
    public static void main(String[] args) {
        long start  = new Date().getTime();
        for (int a = 0; a < 1001; a++) {
            for (int b = 0; b < 1001; b++) {
                for (int c = 0; c < 1001; c++) {
                    if (a + b + c == 1000 && a*a + b*b == c*c){
                        System.out.print(a + " ");
                        System.out.print(b + " ");
                        System.out.print(c + " ");
                        System.out.println(new Date().getTime() - start);
                    }
                }
            }
        }
        System.out.println(new Date().getTime() - start);
    }
}
/*
單位毫秒
0 500 500 3
200 375 425 192
375 200 425 434
500 0 500 524
957
*/

 

JavaScript

單次總耗時1707毫秒

start = new Date().getTime();
// console.log(start)
for (let a = 0; a < 1001; a++) {
    for (let b = 0; b < 1001; b++) {
        for (let c = 0; c < 1001; c++) {
            if (a+b+c == 1000 && a*a + b*b == c*c){
                end = new Date().getTime();
                console.log(a, b, c , end-start);  
            }
        }
    }
}
console.log(new Date().getTime()-start);  // 1708
/*
0 500 500 4
200 375 425 310
375 200 425 624
500 0 500 841
1707
*/

 

C

單次總耗時2744毫秒,比較意外

#include <stdio.h>
#include <time.h>

int main () { clock_t start, finish; double elapsed_time; start=clock(); int a, b, c; for (a=0; a<1001; a++){ for (b=0; b<1001; b++){ for (c=0; c<1001; c++){ if (a+b+c == 1000 && a*a + b*b == c*c){ finish=clock(); printf("%d %d %d %d\n", a, b, c, finish); } } } } finish = clock(); printf("%d \n", finish); return 0; } /* 0 500 500 1 200 375 425 546 375 200 425 1019 500 0 500 1360 2744 */

 

Python

單次總耗時132秒

import time


start = time.time()
for a in range(1001):
    for b in range(1001):
        for c in range(1001):
            if a + b + c == 1000 and a ** 2 + b ** 2 == c ** 2:
                print(a, b, c, time.time()-start)

print(time.time()- start)

"""
0 500 500 0.06199979782104492
200 375 425 25.329999685287476
375 200 425 49.39399981498718
500 0 500 66.0019998550415
132.76599979400635
"""

 

優化后的Pyhton

0.24秒
import math
import time


start = time.time()
for c in range(int(math.sqrt(2) * 1000 - 1000), 1001):
    for a in range(1001 - c):
        b = 1000 - a - c
        if a + b + c == 1000 and a ** 2 + b ** 2 == c ** 2:
            print(a, b, c, time.time()-start)

print(time.time()- start)
"""
200 375 425 0.007999897003173828
375 200 425 0.01900005340576172
0 500 500 0.07599997520446777
500 0 500 0.0819997787475586
0.23999977111816406
"""

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM