簡體   English   中英

1-100,000 的友好數字總和 (AP CS-A)

[英]Sum of amicable numbers from 1-100,000 (AP CS-A)

我們今天在課堂上的任務是找出 1-100000 中所有友好數的和。

 int sum = 0;
        for(int i = 1; i < 100000; i++ ) {
            int a = 1;
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    if (j == (i / j))
                        a += j;
                    else
                        a += (j + i / j);
                }
            }

            int b = 1;
            for (int j = 2; j <= Math.sqrt(a); j++) {
                if (a % j == 0) {
                    if (j == (a / j))
                        b += j;
                    else
                        b += (j + a / j);
                }
            }
            if(a==b) sum += a;
        }
        
        System.out.println(sum);

這是我今天在課堂上制作的代碼。 不幸的是它沒有工作,而不是它的家庭作業。

友好數字定義為: https ://en.wikipedia.org/wiki/Amicable_numbers#:~:text=Amicable%20numbers%20are%20two%20different,is%20(220%2C%20284).&text=For% 20example%2C%20the%20proper%20divisors,aliquot%20sequence%20of%20period%202

我需要在不使用輔助方法和不重復計算可能性的情況下實現這個目標,但我以某種方式不斷得到錯誤的答案。 不幸的是,我們只能將數組和 ArrayList 用於數據結構以保持簡單。

您可以使用布爾數組來跟蹤您已經計算過的值。 這是一個有效的解決方案:

        boolean[] arr = new boolean[100000];
        for(int i = 1; i < 100000; i++ ) {
            int a = 1;
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    if (j == (i / j))
                        a += j;
                    else
                        a += (j + i / j);
                }
            }

            int b = 1;
            for (int j = 2; j <= Math.sqrt(a); j++) {
                if (a % j == 0) {
                    if (j == (a / j))
                        b += j;
                    else
                        b += (j + a / j);
                }
            }

            if(i == b && i != a) {
                if(!arr[i])
                    arr[i] = true;
                if(!arr[b])
                    arr[b] = true;
            }
        }

        int sum = 0;
        for(int i = 0; i < arr.length; i++) {
            if(arr[i] == true) {
                sum += i;
            }
        }
        System.out.println(sum);

為了使這對數字 1 到 n 起作用,您可以用方法參數替換 for 循環中的數組長度和 100000。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM