反复除以最小因子后,在每一步找到 N 的值的总和
给定一个整数N ,任务是在反复除以它的最小因子后找到所有N值的总和。
例子:
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.
方法:给定的问题是一个基于实现的问题,可以通过在[2, √N]范围内迭代并将N除以其最小因子、最大可能次数来解决。保持变量中所有N值的总和,这将是所需的答案。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the sum of all the
// values of N after repeatedly dividing
// it with its smallest factor
int sumValues(int N)
{
// Stores the required answer
int ans = N;
int i = 2;
// Loop to iterate over
// the factors of N
while (N > 1) {
// If i is a factor
if (N % i == 0) {
// Update N
N = N / i;
// Update ans
ans += N;
}
else {
i++;
}
}
// Return Answer
return ans;
}
// Driver function
int main()
{
int N = 10;
cout << sumValues(N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
// Function to find the sum of all the
// values of N after repeatedly dividing
// it with its smallest factor
static int sumValues(int N)
{
// Stores the required answer
int ans = N;
int i = 2;
// Loop to iterate over
// the factors of N
while (N > 1) {
// If i is a factor
if (N % i == 0) {
// Update N
N = N / i;
// Update ans
ans += N;
}
else {
i++;
}
}
// Return Answer
return ans;
}
// Driver function
public static void main (String[] args) {
int N = 10;
System.out.println(sumValues(N));
}
}
// This code is contributed by hrithikgarg03188.
Python3
# python3 program for the above approach
# Function to find the sum of all the
# values of N after repeatedly dividing
# it with its smallest factor
def sumValues(N):
# Stores the required answer
ans = N
i = 2
# Loop to iterate over
# the factors of N
while (N > 1):
# If i is a factor
if (N % i == 0):
# Update N
N = N // i
# Update ans
ans += N
else:
i += 1
# Return Answer
return ans
# Driver function
if __name__ == "__main__":
N = 10
print(sumValues(N))
# This code is contributed by rakeshsahni
C#
// C# program for the above approach
using System;
class GFG
{
// Function to find the sum of all the
// values of N after repeatedly dividing
// it with its smallest factor
static int sumValues(int N)
{
// Stores the required answer
int ans = N;
int i = 2;
// Loop to iterate over
// the factors of N
while (N > 1) {
// If i is a factor
if (N % i == 0) {
// Update N
N = N / i;
// Update ans
ans += N;
}
else {
i++;
}
}
// Return Answer
return ans;
}
// Driver function
public static void Main()
{
int N = 10;
Console.Write(sumValues(N));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
16
时间复杂度: O(√N)
辅助空间: O(1)