Let denote the sum of divisors of an integer . For example, .
Your task is to calculate the sum modulo
Example:
Input: n = 5
Output: 21
Approach
Java
public class SumOfDivisors {public static void main(String[] args) {long n = 5;long ans = 0;for (long l = 1, r, k; l <= n; l = r + 1) {k = n / l;r = n / k;ans = (ans + k * sumOfDivisors(l, r) % MOD) % MOD;}System.out.println(ans);}static long MOD = (long) (1e9 + 7);static long sumOfDivisors(long l, long r) {l %= MOD;r %= MOD;long res = r * (r + 1) / 2 % MOD - l * (l - 1) / 2 % MOD;if (res < 0)res += MOD;return res;}}
C++
#include <bits/stdc++.h>using namespace std;const long long MOD = 1e9 + 7;long long sumOfDivisors(long long l, long long r){l %= MOD;r %= MOD;long long res = r * (r + 1) / 2 % MOD - l *(l - 1) / 2 % MOD;if (res < 0)res += MOD;return res;}int main(){long long n = 5;long long ans = 0;for (long long l = 1, r, k; l <= n; l = r + 1){k = n / l;r = n / k;ans = (ans + k * sumOfDivisors(l, r) % MOD) % MOD;}cout << ans << "\n";return 0;}
No comments:
Post a Comment