Find sum of values of N at each step after repeatedly dividing it with its smallest factor
Last Updated :
02 Mar, 2022
Given an integer N, the task is to find the sum of all values of N after repeatedly dividing it with its smallest factor.
Examples:
Input: N = 5
Output: 6
Explanation: Initially N = 5. The smallest factor of N is 5 itself. Therefore, the value of N will become N/5 = 5/5 = 1. Hence, the sum of all values of N is 5 + 1 = 6.
Input: N = 10.
Output: 16
Explanation: Initially N = 10. The smallest factor of N is 2. Therefore, the value of N will become N/2 = 10/2 = 5. Similarly, in next step, N = N/5 = 5/5 = 1. Hence, the sum of all values of N is 10 + 5 + 1 = 16.
Approach: The given problem is an implementation-based problem and can be solved by iterating in the range [2, √N] and dividing N with its smallest factor, maximum possible times. Maintain the sum of all values of N in a variable which will be the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int sumValues( int N)
{
int ans = N;
int i = 2;
while (N > 1) {
if (N % i == 0) {
N = N / i;
ans += N;
}
else {
i++;
}
}
return ans;
}
int main()
{
int N = 10;
cout << sumValues(N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static int sumValues( int N)
{
int ans = N;
int i = 2 ;
while (N > 1 ) {
if (N % i == 0 ) {
N = N / i;
ans += N;
}
else {
i++;
}
}
return ans;
}
public static void main (String[] args) {
int N = 10 ;
System.out.println(sumValues(N));
}
}
|
Python3
def sumValues(N):
ans = N
i = 2
while (N > 1 ):
if (N % i = = 0 ):
N = N / / i
ans + = N
else :
i + = 1
return ans
if __name__ = = "__main__" :
N = 10
print (sumValues(N))
|
C#
using System;
class GFG
{
static int sumValues( int N)
{
int ans = N;
int i = 2;
while (N > 1) {
if (N % i == 0) {
N = N / i;
ans += N;
}
else {
i++;
}
}
return ans;
}
public static void Main()
{
int N = 10;
Console.Write(sumValues(N));
}
}
|
Javascript
<script>
function sumValues(N) {
let ans = N;
let i = 2;
while (N > 1) {
if (N % i == 0) {
N = Math.floor(N / i);
ans += N;
}
else {
i++;
}
}
return ans;
}
let N = 10;
document.write(sumValues(N));
</script>
|
Time Complexity: O(√N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...