How to find Least Common Multiple (LCM) for two numbers - java

I have used Euclid's method to find the L.C.M for two numbers.
l.c.m=a*b/(gcd(a,b))
How can I do this without using this algorithm?
I have an idea of first getting all factors of these two numbers and storing them in array. Then take 1 element from array 1 and search for it in array2, if it present there then remove it from there and make the result multiply by that num.
Is this OK?

Almost. What's the LCM of 4 and 8? Obviously 8 (23), but in your method you'd find 2. You need to keep track not just of all factors, but also how often they appear.

I believe the algorithm you suggest is a method using a table, check to see if it works for you.

LCM(Least Common Multiple) is always greater than or equal to the larger of the two numbers. So we will first check that the larger number itself a LCM of two numbers by checking that the larger number is divisible by the smaller one , if yes we found the LCM & If no then we will increment the larger number by 1 and check again.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the first Number : ");
int number1 = scan.nextInt();
System.out.print("Enter the second number : ");
int number2 =scan.nextInt();
int multiple;
if(number1 >= number2) {
multiple = number1;
} else {
multiple = number2;
}
Boolean loopContinue = true;
while(loopContinue) {
if(multiple % number1 == 0 && multiple % number2 == 0) {
System.out.println("LCM of Two Numbers is " + multiple);
loopContinue = false;
}
multiple++;
}
}
}

You can get LCM of two number by getting GCD at first.
Here is the solution for the above.
package com.practice.competitive.maths;
import java.util.Scanner;
public class LCMandGCD {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int testCases = scanner.nextInt();
while (testCases-- > 0) {
long number1 = scanner.nextInt();
long number2 = scanner.nextInt();
long gcd = computeGCD(number1, number2);
long lcm = computeLCM(number1, number2, gcd);
System.out.println(lcm + " " + gcd);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static long computeGCD(long number1, long number2) {
while (number1 != number2) {
if (number1 > number2)
number1 -= number2;
else
number2 -= number1;
}
return number2;
}
private static long computeLCM(long number1, long number2, long gcd) {
return (number1*number2)/gcd;
}
}

Related

Java print the recursion in main method

I was wondering when I tried to print the value of recursion in main, the answer was:
Enter the number: 1
2The result is:
How to make the number 2 to the front like,
The result is: 2
import java.util.Scanner;
public class Question4Final {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int a = scan.nextInt();
System.out.printf("The result is: ", multiplication(a));
}
public static int multiplication(int a) {
if (a == 5) {
int multiply = 10 * 6 * 2;
System.out.print(multiply);
} else if (a == 4) {
int multiply2 = 6 * 2;
System.out.print(multiply2);
} else if (a == 1) {
System.out.print("2");
}
return a;
}
}
To call the method:
System.out.printf("The result is: ", multiplication(a));
first the arguments must be evaluated, so multiplication(a) is executed before System.out.printf("The result is: ", multiplication(a)). Since multiplication(a) prints something, that printing takes place before "The result is:" is printed.
You should change multiplication(a) to simply return the result without printing it. Then use System.out.println("The result is: " + multiplication(a)) to print the result.
Note the you have to change the value returned by multiplication(a), since currently you return a, which is not the value printed by that method.
You have 2 issues in your code.
First is you are printing the value of 'multiply' in your static method :
public static int multiplication(int a){
System.out.print(multiply);
That is a reason why it is printing 2 before the statement :
2The result is:
2nd issue is you are calling the method multiplication in the print statement :
System.out.printf("The result is: ", multiplication(a));
That is not how to print the result by calling the method.
I have taken your example and run the below code. You can check this code.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int a = scan.nextInt();
int product = multiplication(a);
System.out.println("The result is : " +product);
}
public static int multiplication(int a){
int multiply = 0;
if(a == 5){
multiply = 10 * 6 * 2;
}else if(a == 4){
multiply = 6 * 2;
}else if(a == 1){
multiply = 2;
}
return multiply;
}
}
Below are the outputs on different options :
Enter the number: 4
The result is : 12
Enter the number: 5
The result is : 120
Enter the number: 1
The result is : 2

Random number (1-100) picking loop program | Understanding methods

what I am looking to do is create a program that will randomly pick an integer between 1 and 100. Then, ask the user to guess it. Loop until they do, and after each incorrect guess tell them if they are too high or too low. I want to use two different methods to validate their input. One to test whether it is a valid int, the other to test the range (1-100). This second will require another parameter for the high range value.
The problems I am having:
1. I do not understand why I have to enter a number multiple times before my while (guess != a) { is triggered.
Example from console :
I am thinking of a number from 1 to 100 ... guess what it is ?6
I am thinking of a number from 1 to 100 ... guess what it is ?6
I am thinking of a number from 1 to 100 ... guess what it is ?6
6
higher!
2. how could I use my check methods and have them pertain to my while guess loop?
Example from console again:
`I am thinking of a number from 1 to 100 ... guess what it is? 10001
I am thinking of a number from 1 to 100 ... guess what it is? 10001
Error! Must be less than 100
I am thinking of a number from 1 to 100 ... guess what it is? 10001
100
lower!
10001
lower!`
{What I have full written currently}
package labbs;
import java.util.Scanner;
public class Lab12 {
public static double getDoubleGreaterThan(double low, Scanner input, String prompt) {
double num;
num = getDouble(input,prompt);
if(num <= low)
System.out.println("Error! Must be greater than 1");
num = getDouble(input,prompt);
if (num > 100)
System.out.println("Error! Must be less than 100");
num = getDouble(input,prompt);
return num;
}
public static double getDouble(Scanner input, String prompt) {
boolean OK;
double val=0;
do {
System.out.print(prompt);
OK = true;
try {
val = input.nextDouble();
}
catch(Exception e) {
OK = false;
System.out.println("Error! Invalid input. Must be a double value");
input.next();
}
}while(! OK);
return val;
}
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
double output, letscheck;
int count=0, guess=0;
int a=1 + (int) (Math.random() * 99);
letscheck = getDoubleGreaterThan(-0.9, keyboard,"I am thinking of a number from 1 to 100"
+ " ... guess what it is ?");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess > a) {
System.out.println("lower!");
} else if (guess < a) {
System.out.println("higher!");
}
}
System.out.println("Congratulations. You guessed the number with "
+ count + " tries!");
}
}
1. Query: You have just missed bracket in getDoubleGreaterThan()method as after if statement block always working not on the basis of input so change your code like below:
public static double getDoubleGreaterThan(double low, Scanner input, String prompt) {
double num;
num = getDouble(input,prompt);
if(num <= low){
System.out.println("Error! Must be greater than 1");
num = getDouble(input,prompt);
}
if (num > 100){
System.out.println("Error! Must be less than 100");
num = getDouble(input,prompt);
}
return num;
}

Type mismatch:could not convert from int to boolean

In the if statement, within the argument I get an error saying "type mismatch, could not convert from int to boolean". Please provide a solution.
public static void main(String[] args) {
Scanner sathya1 = new Scanner(System.in);
System.out.println("Enter the numbers");
int x = (sathya1.nextInt());
int y = (sathya1.nextInt());
int addition = x+y;
int subtraction = x-y;
int multiplication = x*y;
float division = x/y;
if(sathya1.nextInt(addition){
System.out.println("The number is " +addition);
elseif(sathya1.nextInt(subtraction)){
System.out.println("The number is " +subtraction);
elseif(sathya1.nextInt(multiplication)){
System.out.println("The number is " +multiplication);
elseif(sathya.1nextInt(division)){
System.out.println("The number is " +division);
}
}
}
}
}
}
The line
if(sathya1.nextInt(addition){
makes no sense. It's like saying "if 12". The same goes for the other lines. In addition, you're missing a closing ), among lots of other problems.
Maybe you mean:
import java.util.Scanner;
public class BasicArithmetic
{
public static void main(String[] args)
{
//create a scanner for keyboard input
Scanner sathya1 = new Scanner(System.in);
//ask user for the operation to be used
System.out.print("Please enter the corresponding number to be used \n(1)for Addition,(2)for Subtraction,(3)for Multiplication,(4)for Division:");
int enteredNumber = sathya1.nextInt();
//get the two numbers to be used
System.out.println("Enter the numbers");
float x = sathya1.nextFloat();
float y = sathya1.nextFloat();
//arithmetic operations of the two numbers
float addition = x+y;
float subtraction = x-y;
float multiplication =x*y;
float division = x/y;
//if..else statement
if(enteredNumber==1)
{
System.out.println("The sum of the two number is "+addition);
}
else if(enteredNumber==2)
{
System.out.println("The subtraction of the two number is "+subtraction);
}
else if(enteredNumber==3)
{
System.out.println("The product of the two number is "+multiplication);
}
else if(enteredNumber==4)
{
System.out.println("The quotient of the two number is "+division);
}
else
{
System.out.println("Please enter the correct corresponding number");
}
}
}

Java Factorial using GUI only returns the first output

I have a program which should generate the factorial of any given number n.
When the user enters a number, the output is the factorial for every number entered after that into the calculator.
The code compiles fine but the calculator will not calculate any factorial except for the first.
As i can't use recursion for solving this problem please post only answers without using recursion.
Here's the code:
import javax.swing.JOptionPane;
public class Assignment7
{
public static void main(String[] args)
{
int number1;
int factorial = 1;
String message;
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
do
{
message = String.format("The factorial of %d is: %d", number1, factorial);
JOptionPane.showMessageDialog(null, message);
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
}
while(number1 != 1);
}
}
This code
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
needs to be repeated for each input.
I suggest that your GF put this into a method that can be called and the method will return the result.
import javax.swing.JOptionPane;
public class Assignment7
{
public static void main(String[] args)
{
int number1;
int factorial = 1;
String message;
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
do
{
message = String.format("The factorial of %d is: %d", number1, factorial);
JOptionPane.showMessageDialog(null, message);
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
factorial = 1;
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
}
while(number1 != 1);
}
}
You have to reset the number and the factorial to get the right factorial.
Also i would consider to use a head-controlled loop. Because it's easier to understand what is going on. Also maybe don't put the Inputdialog and the Parsing of the string to int into one line, it makes it a lot easier to handle wrong user-inputs, what you also should be doing.
Here my solution:
import javax.swing.JOptionPane;
class Assignment7 {
public static void main(String[] args) {
int number1 = 0;
int factorial = 1;
String message;
while (number1 != 1) {
String positiveInteger = JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : ");
// You could check if there was a user-input and also later check if it's a number.
if (positiveInteger.length() > 0) {
number1 = Integer.parseInt(positiveInteger);
}
for (int i = 1; i <= number1; i++) {
factorial = factorial * i;
}
message = String.format("The factorial of %d is: %d", number1, factorial);
JOptionPane.showMessageDialog(null, message);
//Reset everything
number1 = 0;
factorial = 1;
message = "";
}
}
}

How do I use a function involving integers?

We have an assignment in class to create a greatest common divider (gcd) program using functions. I missed out on the lesson where we learned how to properly use them. I finished the part that actually does the division but I don't know how to separate it into a function and have it work. I'd like to have the input in the main class and the process in function.
This is what I have, it does not work when I run it
package gcd.function.java.program;
import java.util.Scanner;
/**
*
* #author sarah_000
*/
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
int div;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
System.out.printf("The GCD is %d ", div);
}
public static void GCDFunction() {
if(num1 > num2)
div = num2;
else div = num1;
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
}
}
Any tips or help you can give to me will be greatly appreciated, I'm very new
You declare two parameters and modify the return type in your GCDFunction like this:
public static int GCDFunction(int num1, int num2)
You are currently trying to access the variables in the main method but are out of scope.
Also, you never actually call your GCDFunction
Think of it like passing functions in math. The GCDFunction() has to receive the numbers into the function so we do
public static void GCDFunction(int num1, int num2)
That also lets Java know the type it is, type int. And your java variables are scoped inside of the functions so you have to print the output in the function that created the variable in your scenario.
So once you have that function set up to receive the variables and output after processing, you call the function in the main with a
GCDFunction(num1, num2);
Where num1 and num2 are the variables that have your integers stored in.
The end result after a little rearranging looks like this.
import java.util.Scanner;
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
GCDFunction(num1, num2);
}
public static void GCDFunction(int num1, int num2) {
int div;
if(num1 > num2){
div = num2;
}
else{ div = num1;}
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
System.out.printf("The GCD is %d ", div);
}
Trying to give you a example of how the code should be to take in variable number of parameters.
public int gcd(Integer... numbers) {
int gcd = 1;
int miNNumber=Collections.min(Arrays.asList(numbers));
boolean isDivisible;
for(int i=2; i<=miNNumber;i++) {
isDivisible=true;
for(Integer eachNumber : numbers) {
if(eachNumber%i!=0) {
isDivisible=false;
break;
}
}
if(isDivisible) {
gcd=i;
}
}
return gcd;
}
You can call it
gcd(10, 200, 400);
or
gcd(10, 200, 400, 4000, 40);

Categories

Resources