-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSum of all divisors from 1 to n
62 lines (53 loc) · 1.16 KB
/
Sum of all divisors from 1 to n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
Given a positive integer N., The task is to find the value of Σi from 1 to N F(i) where function F(i) for the number i is defined as the sum of all divisors of i.
Example 1:
Input:
N = 4
Output:
15
Explanation:
F(1) = 1
F(2) = 1 + 2 = 3
F(3) = 1 + 3 = 4
F(4) = 1 + 2 + 4 = 7
ans = F(1) + F(2) + F(3) + F(4)
= 1 + 3 + 4 + 7
= 15
Example 2:
Input:
N = 5
Output:
21
Explanation:
F(1) = 1
F(2) = 1 + 2 = 3
F(3) = 1 + 3 = 4
F(4) = 1 + 2 + 4 = 7
F(5) = 1 + 5 = 6
ans = F(1) + F(2) + F(3) + F(4) + F(5)
= 1 + 3 + 4 + 7 + 6
= 21
Your Task:
You don't need to read input or print anything. Your task is to complete the function sumOfDivisors() which takes an integer N as an input parameter and returns an integer.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
solution:
class Solution{
static long f(int n){
int c = 0;
int s =0;
for(int i=1;i<=n;i++){
if(n%i == 0){
c++;
s+=i;
}
}
return s;
}
static long sumOfDivisors(int N){
int sum=0;
for(int i=1;i<=N;i++){
sum +=f(i);
}
return sum;
}
}