JAVA Program to print common factors of two number
A factor is a number that divides into another number exactly and without leaving a remainder. The number 12 has six factors:
1 2 3 4 6 12
If 12 is divided by any of the six factors then the answer will be a whole number.
For example: 12 ÷ 2 =6 12 ÷ 3 = 4
Two numbers with common factor
factors of 6 are : 1 2 3 6 and factors of 12 are: 1 2 3 4 6 12
Both have 1 2 3 6 common........
So their common factors will be 1 2 3 6
Join Us
For those who prefer reading on mobile, we have Telegram channel and WhatsApp group that will allow you to receive updates, announcements, and links to our stories straight to your mobile device..
Steps to be followed for finding the largest factors of a number.
- Input two number from user, let it be num1 and num2.
- Now create a loop which starts from i=1 and ends at i<= minimum of num1 and num2 .
- Inside Loop if num1%i==0 && num2%i==0 . Print i
Sounds Good ? Let's get started
CODE:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /* * Author: TheSchoolProgrammer * www.theschoolprogrammer.com * Question:Write a program to accept two numbers and print their common factors. */ import java.util.*; public class CommonFact { public static void main() { Scanner sc=new Scanner(System.in); System.out.println("ENTER 1st NUMBER"); int num1=sc.nextInt(); System.out.println("ENTER 2nd NUMBER"); int num2=sc.nextInt(); int i; for(i=1;i<=Math.min(num1,num2);i++) { if(num1%i==0 && num2%i==0) System.out.print(i+" "); } } } |
Output:
Example 1 Input: ENTER 1st NUMBER 48 ENTER 2nd NUMBER 36 Output:1 2 3 4 6 12 Example 2 Input:ENTER 1st NUMBER 18 ENTER 2nd NUMBER 12 Output:1 2 3 6
Found this useful? Share with your friends. Share
Comments