簡単 0件解決済み 正答率0%

Sum of Proper Divisors

Add up every divisor of n that is smaller than n.

このチャレンジで学べること

  • Find divisors in pairs
  • Stop the loop at the square root
  • Avoid counting a square root divisor twice

問題

翻訳を表示

The proper divisors of n are the positive divisors other than n itself. For 12 they are 1, 2, 3, 4 and 6. Their sum (sometimes called the aliquot sum) tells whether a number is perfect, abundant or deficient. Divisors come in pairs d and n / d, so you only need to try values of d up to the square root of n.

Implement sum_of_proper_divisors(n).

Input

n: A positive integer.

Output

Return the sum of all positive divisors of n that are less than n. For n = 1 there are none, so return 0.

制約

1 ≤ n ≤ 10^12

例

例 1
入力:
n = 12

期待される出力:
expected = 16
入力:
long long n = 12;

期待される出力:
long long expected = 16;
入力:
long n = 12;

期待される出力:
long expected = 16;

解説

1 + 2 + 3 + 4 + 6 = 16.

例 2
入力:
n = 28

期待される出力:
expected = 28
入力:
long long n = 28;

期待される出力:
long long expected = 28;
入力:
long n = 28;

期待される出力:
long expected = 28;

解説

1 + 2 + 4 + 7 + 14 = 28, so 28 is a perfect number.

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

If d divides n, then n / d divides n too.

ヒント 2

Only try d up to the square root of n, adding both members of each pair.

ヒント 3

Leave n itself out, and add the square root only once when n is a perfect square.

目安の計算量

O(sqrt n) time, O(1) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。