求一个数的偶数因子之和的Java程序

给定一个数n,任务是求一个数的偶数因子和。

null

例如:

Input : 30
Output : 48
Even dividers sum 2 + 6 + 10 + 30 = 48

Input : 18
Output : 26
Even dividers sum 2 + 6 + 18 = 26

设p1,p2,…pk为n的素因子。。ak是p1,p2。。pk分别除以n,也就是说,我们可以把n写成 n=(p1 a1 )*(p2) a2 )*…(主键) ak ) .

Sum of divisors = (1 + p1 + p12 ... p1a1) * 
                  (1 + p2 + p22 ... p2a2) *
                  ...........................
                  (1 + pk + pk2 ... pkak) 

如果数字是奇数,那么就没有偶数因子,所以我们只返回0。

如果这个数是偶数,我们使用上面的公式。我们只需要忽略2 0 .所有其他项相乘产生偶数因子和。例如,考虑n=18。它可以写成2 1. 3. 2. 所有因素中的太阳是(2) 0 + 2 1. )*(3 0 + 3 1. + 3 2. ).如果我们移除2个 0 然后我们得到 偶数因子之和(2)*(1+3+3) 2. ) = 26.

为了去除偶数因子中的奇数,我们忽略2 0 什么是1。经过这一步,我们只得到了偶数因子。请注意,2是唯一的偶数素数。

// Formula based Java program to
// find sum of all divisors of n.
import java.util.*;
import java.lang.*;
public class GfG {
// Returns sum of all factors of n.
public static int sumofFactors( int n)
{
// If n is odd, then there
// are no even factors.
if (n % 2 != 0 )
return 0 ;
// Traversing through all prime
// factors.
int res = 1 ;
for ( int i = 2 ; i <= Math.sqrt(n); i++) {
int count = 0 , curr_sum = 1 ;
int curr_term = 1 ;
// While i divides n, print i and
// divide n
while (n % i == 0 ) {
count++;
n = n / i;
// here we remove the 2^0 that
// is 1. All other factors
if (i == 2 && count == 1 )
curr_sum = 0 ;
curr_term *= i;
curr_sum += curr_term;
}
res *= curr_sum;
}
// This condition is to handle the
// case when n is a prime number.
if (n >= 2 )
res *= ( 1 + n);
return res;
}
// Driver function
public static void main(String argc[])
{
int n = 18 ;
System.out.println(sumofFactors(n));
}
}
/* This code is contributed by Sagar Shukla */


输出:

26

请参阅完整的文章 求一个数的偶数因子之和 更多细节!

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享