
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 Minimum Sum of Factors of a Number in Java
In mathematics, the factors of a number are the integers that divide the number without leaving a remainder. For a given number, finding the minimum sum of its factors involves identifying a pair of factors whose sum is the smallest among all possible factor pairs. In this article, we will learn to find the minimum sum of factors of a number we will be using the Integer class and Math class in Java ?
Integer class
The Java Integer class serves as a wrapper for the primitive int type, encapsulating a single integer value within an object.
For Integer.MAX_VALUE, which provides the maximum value an int can hold.
int minSum = Integer.MAX_VALUE;
Math class
The java.lang.Math class provides methods to perform fundamental numeric operations, including exponential calculations, logarithms, square roots, and trigonometric functions.
For Math.sqrt(n), used to calculate the square root of the number to limit the iteration range to potential factors
for (int i = 1; i <= Math.sqrt(n); i++)
Problem Statement
Given a positive integer n, the task is to find the minimum sum of two factors a and b, such that:
aÃb = n
Both a and b are integers and a, b ? 1.
The goal is to minimize a + b.Java program to find minimum sum of factors of a number
This Java program finds the minimum sum of factor pairs of a given number by iterating up to its square root and checking for divisors. It uses the Math.sqrt function and Integer.MAX_VALUE for efficient computation and comparison.
Example
To find minimum sum of factors of a number, the Java code is as follows ?
public class MinimumSumOfFactors { // Method to find the minimum sum of factors public static int findMinimumSumOfFactors(int n) { int minSum = Integer.MAX_VALUE; // Iterate over possible factors up to the square root of n for (int i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { // Check if i is a factor int pairFactor = n / i; // Calculate the pair factor // Calculate the sum of the factor pair int sum = i + pairFactor; // Update the minimum sum if (sum < minSum) { minSum = sum; } } } return minSum; } public static void main(String[] args) { int number = 36; // Example input // Find and display the minimum sum of factors int minSum = findMinimumSumOfFactors(number); System.out.println("The minimum sum of factors of " + number + " is: " + minSum); } }
Output
The minimum sum of factors of 36 is: 12
Time Complexity: O(?n).
Space Complexity: O(1).