【Java】统计随机抽出两个小于等于N的互异正整数的频率
生活随笔
收集整理的這篇文章主要介紹了
【Java】统计随机抽出两个小于等于N的互异正整数的频率
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
任務要求
計算兩個隨機選取的、小于或者等于N的互異正整數的概率。
事實上,當N增大時,結果將趨于6π2\frac{6}{π^2}π26?
最后會測一下效率。
Java編程實現
public class Main {public static int gcd(int m, int n) {if(m < n) {return gcd(n, m);}if(n == 0) {return m;}return gcd(n, m % n);}public static double probRelPrime(int n) {int rel = 0, tot = 0;for(int i = 1; i <= n; i++) {for(int j = i + 1; j <= n; j++) {tot++;if(gcd(i, j) == 1) {rel++;}}}return (double)rel / tot;}public static void main(String[] args) {for(int n = 500; n <= 64000; n *= 2) {long start = System.currentTimeMillis();double prob = probRelPrime(n);//System.out.println(prob);long end = System.currentTimeMillis();if(n == 500) {continue;}long elapsed = (end - start);System.out.print( String.format("%4d", n));System.out.print( String.format("\t%d", elapsed));System.out.print( String.format("\t%.9f", elapsed / (double)n / n));System.out.print( String.format("\t%.12f", elapsed / (double)n / n / n));System.out.print( String.format("\t%.9f", elapsed / (double)n / n / (Math.log10(n) / Math.log10(2))));System.out.println();}}}測試結果
1000 31 0.000031000 0.000000031000 0.000003111 2000 93 0.000023250 0.000000011625 0.000002120 4000 453 0.000028313 0.000000007078 0.000002366 8000 1896 0.000029625 0.000000003703 0.000002285 16000 8199 0.000032027 0.000000002002 0.000002293 32000 35568 0.000034734 0.000000001085 0.000002321 64000 152640 0.000037266 0.000000000582 0.000002334 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的【Java】统计随机抽出两个小于等于N的互异正整数的频率的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【数据结构与算法】实践 构造病种树结构
- 下一篇: 【需求工程】剖析BPMN