DEV Community

Saurabh Kumar
Saurabh Kumar

Posted on

Maths for Coders : Chapter 1

Starting a thread where I will be adding some common math problems expected from developers in interview rounds or aptitude tests.

These will always come in handy - so I have added the cleanest version of some common functions

  • find all prime factors
  • check if a Number is odd-even
  • find LCM of n elements
  • find HCF of n elements
import java.util.ArrayList;
import java.util.List;
public class MathsForCodersV1 {
/**
* Brief idea about the logic behind the code-
* <p>
* LCM(a,b)=a*b/HCF(a,b)
*
* <p>
* LCM of 10, 18, 24 =>
* 10 = 2 x 5
* 18 = 2 x 3^2
* 24 = 2^3 x 3
* <p>
* so for lcm we take all unique primes and there max powers => 2^3 x 3^2 x 5 = 8 x 9 x 5 = 360
* </p>
*/
public static int smallestNumberDivisibleBy(int[] list) {
int lcm = 1;
int first = lcm;
for (int i : list) {
lcm = (first * i) / hcf(first, i);
first = lcm;
}
return lcm;
}
protected static List<Integer> getPrimeFactors(int n) {
final List<Integer> result = new ArrayList<>();
// handle 2
while (n % 2 == 0) {
n /= 2;
result.add(2);
}
// handle rest
for (int i = 3; i <= Math.sqrt(n); i += 2) {
// if ((i & 1) != 0) { // already odd by design
while (n % i == 0) {
n /= i;
result.add(i);
}
// }
}
// This condition is to handle the case when n is a prime number greater than 2 and Math.sqrt(n/2)
if (n > 2) {
result.add(n);
}
return result;
}
/**
* <p>
* HCF of 10, 24
* 10 = 2 x 5
* 24 = 2^3 x 3
* HCF = 2 (the only common factor
* </p>
*/
static int hcf(int a, int b) {
if (b == 0) {
return a;
}
return hcf(b, a % b);
}
static boolean isOdd(int num) {
return (num & 1) != 0;
}
}

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay