
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Sum of Even Factors of a Number in Java
In this article we'll find the sum of even factors of a given number using Java. We'll start by checking if the number is even, then identify all of its factors, sum up those that are even, and finally display the result.
Problem Statement
Write a Java program to find the sum of even factors of a number. Below is the demostration of the same ?
Input
num=16
Ouput
The sum of even factors of the number is
30
Steps to find sum of even factors of a number
Following are the steps to find sum of even factors of a number ?
- Start with import the required classes.
- Check that the number is even or not, return 0.
- Factorize the number to do we will use a loop to find all factors up to the square root of the number.
- Sum up the even factors
- Display the sum of even factors.
Java program to find sum of even factors of a number
To find the sum of even factors of a number, the Java code is as follows ?
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
Code Explanation
First we will import all the classes from java.util and java.lang package after that we will initialize a class named Demo contains a function named ?factor_sum'. It begins by checking if the number is even. If not, it returns 0. Using a for loop it iterates through possible factors and a nested while loop factorizes the number. It updates the sum of even factors, and after the loop it multiplies the result by any remaining prime factors. The main method initializes the number calls factor_sum and prints the result.