Skip to main content

Posts

Showing posts from June, 2020

Prime Factors of a given number

Write a program to find all prime factors of a given number.  The program should print the factors of a number which are prime.  One way of writing this is  If the number is divisible by 2, repeatedly divide the number by 2 until it is no longer divisible by 2. Print 2 as a factor if number is divisible.  In a loop for values of i from 3 to n in steps of 2, find if a number is divisible by i. If yes repeatedly divide by i as long as number is divisible.    void printFactors(int num){           if(num%2==0){             System.out.println("2 ");             while (num%2==0)              num = num/2;           }              ...

Program to find LCM

Write a program to find LCM of two numbers. LCM - is the least common multiple. If the numbers are 20 and 18, then LCM of these numbers is 90. The easiest and fastest way of finding LCM is finding GCD(greatest common divisor or highest common factor - the largest number which divides two numbers) and then dividing GCD by product of numbers. LCM * GCD = n1 * n2 Now to find GCD we can use the following algorithm. If num1 is divisible by num2 return num2 If not, return gcd of num2 and num2%num1  set num2 = num1%num2 set num1 = num2 find gcd of num1 and num2 and return it.      We will write gcd as a recursive function. A recursive function is a function which calls itself. Similar to our factorial program.      int gcd(int n1,int n2){          if(n1%n2==0)             return n2;          return gcd(n2,n1%n2);...