Java Program to Find sum of even factors of a number


To find sum of even factors of a number, the Java code is as follows −

Example

 Live Demo

import java.util.*;
import java.lang.*;
public class Demo{
   public static int factor_sum(int num){
      if (num % 2 != 0)
      return 0;
      int result = 1;
      for (int i = 2; i <= Math.sqrt(num); i++){
         int count = 0, current_sum = 1;
         int current_term = 1;
         while (num % i == 0){
            count++;
            num = num / i;
            if (i == 2 && count == 1)
               current_sum = 0;
            current_term *= i;
            current_sum += current_term;
         }
         result *= current_sum;
      }
      if (num >= 2)
         result *= (1 + num);
      return result;
   }
   public static void main(String argc[]){
      int num = 36;
      System.out.println("The sum of even factors of the number is ");
      System.out.println(factor_sum(num));
   }
}

Output

The sum of even factors of the number is
78

A class named Demo contains a function named ‘factor_sum’. This function finds the factors of a number, and adds up the even factors and returns this value as the output. In the main function, the number whose even factors need to be found is defined, and the function is called on this number. The relevant message is displayed on the console.

Updated on: 08-Jul-2020

588 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements