I came across a question which says to input two numbers and print
their GCD(Greatest common Divisor).
Here is the code which i wrote:
import java.io.*;
class gcd {
public static void main(String args[]) throws IOException{
static int m=0;
static int gcd=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter two integers");
String s1=br.readLine();
int g1=Integer.parseInt(s1);
String s2=br.readLine();
int g2=Integer.parseInt(s2);
int maxim=Math.max(g1,g2);
int minim=Math.min(g1,g2);
while(m!=0){
m = maxim % minim;
if(m == 0){
gcd=minim;
}
maxim=minim;
minim=m;
}
System.out.println("GCD="+minim);
}
}
If i enter two numbers, say 25 and 45, the GCD result should be 5. However, the output is coming as 25.
Please find out the error in my code.
You should still be getting compilation errors with declaration of 'm' and 'gcd' as static. You do not need to declare them static.
The other bug you have is, you are initializing m to 0, and the while loop statement is
while(m!=0){
so the while loop will not get executed even once since the condition 'm != 0' is false. This explains why the output is 25 when your input is 45 and 25. Consider using a do-while loop so that the loop gets executed at least once. Another bug is that your final print statement is printing the value of 'minim', is that what you want? Shouldn't you be printing the variable that stores the final gcd value. I have given you all the hints so that you have the satisfaction of fixing the bugs by yourself!
Firstly, I will recommend to create a function and then do the calculation.
Your code is incorrect
maxim = 45
minim = 25
m = maxim %minim // m=45%25 = 20
m !=0
maxim = minim // maxim=minim=25
m=minim // m=25
//In your next iteration
maxim=25
minim=25
m = maxim %minim // m=25%25 = 0
m==0
gcd= minim // i.e 25
So, your code is incorrect
Try this -
public static void gcd(int a, int b)
{
if(a==b)
return a;
else if(a>b)
return gcd(a-b,b);
else
return gcd(a,b-a);
}
Related
Need help with this problem, I am very bad at recursion. I need to write a method that does this:
The input variable X is an integer between 1 and 50. The function should return as Y the X-th term of a sequence defined recursively by:
f(1) = 1
f(2) = 3
f(X) = 2*f(X-1) – 2*f(X-2) for X = 3,4,5,...
Your function code should use recursion (not a loop)
TBH I dont even know where to get started. Any help would be appreciated. Here is my current code:
package p1parta;
import java.util.Scanner;
public class RecursiveSeq
{
public static void main(String args[])
{
System.out.println("Please enter a number:");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
System.out.println(sequence(x));
}
public static int sequence(int x)
{
if(x == 1){
return 1;
}
if (x == 2){
return 3;
}
return 2 * sequence(x - 1) - 2 * sequence(x - 2);
}
}
I tried to implement the solution shown but the output I get from the program do not match what I am calculating by hand. In fact just testing inputs 3,4,5,and 6 The only one that matches is 5
Your problem is a perfect use case for recursion. In general the recursive pattern is:
func(context)
if simple case
return simple answer
else
call func(simpler context)
and return combined results
Have a go at implementing using this pattern and come back if you have issues.
My assignment is to find a way to display all possible ways of giving back change for a predetermined value, the values being scanned in from a txt file. This must be accomplished by Recursive Backtracking otherwise my solution will not be given credit. I will be honest in saying I am completely lost on how to code in the appropriate algorithm. All I know is that the algorithm works something like this:
start with empty sets.
add a dime to one set.
subtract '10' from my amount.
This is a negative number, so I discard that set: it is invalid.
add a nickel to another (empty) set.
subtract '5' from my amount.
This equals 2; so I'll have to keep working on this set.
Now I'm working with sets that already include one nickel.
add a dime to one set.
subtract '10' from my amount.
This is a negative number, so I discard that set: it is invalid.
repeat this with a nickel; I discard this possibility because (2 - 5) is also negative.
repeat this with a penny; this is valid but I still have 1 left.
repeat this whole process again with a starting set of one nickel and one penny,
again discarding a dime and nickel,
and finally adding a penny to reach an amount of 0: this is a valid set.
Now I go back to empty sets and repeat starting with a nickel, then pennies.
The issue is I haven't the slightest clue on how or where to begin, only that that has to be accomplished, or if any other solutions are apparent.
This is my code thus far:
UPDATED
import java.io.*;
import java.util.*;
import java.lang.*;
public class homework5 {
public static int penny = 1;
public static int nickle = 5;
public static int dime = 10;
public static int quarter = 25;
public static int halfDollar = 50;
public static int dollar = 100;
public static int change;
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Integer> coinTypes = new ArrayList<Integer>();
Integer i;
File f = new File (args[0]);
Scanner input = new Scanner(f);
input.nextLine();
while(input.hasNextInt()) {
i = input.nextInt();
coinTypes.add(i);
}
change = coinTypes.get(coinTypes.size()-1);
coinTypes.remove(coinTypes.size()-1);
System.out.println("Found change"); //used for debugging
System.out.println("Change: " + change);
System.out.println(coinTypes);
}
boolean findChange(int change, List<Integer> coinTypes,
List<Integer> answerCoins) {
if(change == 0) {
return true;
}
if(change < 0) {
return false;
} else {
for(Integer coin : coinTypes) {
if(findChange(change - coin, coinTypes, answerCoins)){
answerCoins.add(coin);
return true;
}
}
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) {
System.out.println(answer);
} else { System.out.println("No change found");
}
return false;
}
}
Here is the input file that I scan in
java homework5 hwk5sample1.txt
// Coins available in the USA, given in cents. Change for $1.43?
1 5 10 25 50 100
143
OUTPUT
Found change
Change: 143
[1, 5, 10, 25, 50, 100]
So using the numbers in my coinTypes ArrayList, I need a generic code algorithm to show all possible ways of receiving, for example, 143 ($1.43) back in change using the coins in the file with all pennies being the last way to show it.
Please do not think I want you to write me the algorithm, I am simply wanting help writing one otherwise I will learn nothing. Thank you all for any answers or help you can give it means a lot to me! Please let me know if i missed anything or you need more info
The example that you walk through seems to be mostly correct. The only error is this: again discarding a dime and nickel, which should be again discarding a *penny* and nickel (but I think that's just a typo.)
To write a recursive backtracking algorithm, it is useful to think of the recursive call as solving a subproblem of the original problem. In one possible implementation of the solution, the pseudocode looks like this:
/**
* findChange returns true if it is possible to make *change* cents of change
* using the coins in coinTypes. It adds the solution to answerCoins.
* If it's impossible to make this amount of change, then it returns false.
*/
boolean findChange(int change, List<Integer> coinTypes, List<Integer> answerCoins) {
if change is exactly 0: then we're done making change for 0 cents! return true
if change is negative: we cannot make change for negative cents; return false
otherwise, for each coin in coinTypes {
// we solve the subproblem of finding change for (change - coin) cents
// using the recursive call.
if we can findChange(change - coin, coinTypes, answerCoins) {
// then we have a solution to the subproblem of
// making (change - coins) cents of change, so:
- we add coin to answerCoins, the list of coins that we have used
- we return true // because this is a solution for the original problem
}
}
//if we get to the next line, then we can't find change for any of our subproblems
return false
}
We would call this method with:
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) {
System.out.println(answer); // your desired output.
}
else {
System.out.println("Can't find change!");
}
package helloworld;
public class windspeed {
public static void main(String args[]) {
int t = Integer.parseInt(args[44]); //this is the array input for temperature
int v = Integer.parseInt(args[15]); //this is the array input for wind speed
double x = Math.pow(v, 0.16); //this is the exponent math for the end of the equation
if (t < 0) {
t = t*(-1); //this is the absolute value for temperature
}
double w = (35.74 + 0.6215*t)+((0.4275*t - 35.75)* x); //this is the actual calculation
if (t<=50 && v>3 && v<120) { //this is so the code runs only when the equation works
System.out.println(w);
}
if (t>50 || v<3 || v>120){
System.out.println("The wind chill equation doesn't work with these inputs, try again.");
}
}
}
This gives me an ArrayIndexOutOfBounds error. It doesn't matter what I put in the [] I get an error... why? and how can I fix it?
The reason is
int t = Integer.parseInt(args[44]);
Do you have 45 arguments?
The problem here is the way in which you are creating the arrays:
int t = Integer.parseInt(args[44]); //this is the array input for temperature
int v = Integer.parseInt(args[15]); //this is the array input for wind speed
args refers to the command line arguments that are passed to the main() method of your program. If you try to parse args[44] when there aren't 45 arguments (0 indexing, remember ?) you will end up assigning null to your array.
So, all you will later end up with is an ArrayIndexOutOfBoundsException becuase you cannot index a null array.
int t[] = new int[44]; // please notice the brackets
int v[] = new int[15]; //this is the array input for wind speed
The above method shall suffice if all you need is the size
Arrays in Java are int[] t or int t[]. Either of them will do but the brackets need to be there.
Use Math.abs() to find the absolute value. Saves you the if()
int t = Integer.parseInt(args[44]); //this is the array input for temperature
int v = Integer.parseInt(args[15]); //this is the array input for wind speed
args i.e. args is the command line arguments for main method. Do you have 45 elements inside the args if not than it will throw ArrayIndexOutOfBounds.
To know the length please use:
args.length
Than you can proceed. Hope it helps.
In these lines :
int t = Integer.parseInt(args[44]); //this is the array input for temperature
int v = Integer.parseInt(args[15]); //this is the array input for wind speed
You say that you run your program with at least 45 parameters!! where on the 15. place is wind speed and on the 44. is temperature.
You probably running program with NO parameters at all or with one.
Note that if you run program with parameters : "hello world how are you" the program would have args of size 5 with having hello in args[0], world in args[1] etc.
What you have now is:
- take the 15th command line argument and cast to to Integer;
- take the 44th command line argument and cast it to Integer.
Are you sure that it is what you need?
New to Java, basically started yesterday.
Okay, so here's the thing.
I'm trying to make an 'averager', if you wanna call it that, that accepts a random amount of numbers. I shouldn't have to define it in the program, it has to be arbitrary. I have to make it work on Console.
But I can't use Console.ReadLine() or Scanner or any of that. I have to input the data through the Console itself. So, when I call it, I'd type into the Console:
java AveragerConsole 1 4 82.4
which calls the program and gives the three arguments: 1, 4 and 82.4
I think that the problem I'm having is, I can't seem to tell it this:
If the next field in the array is empty, calculate the average (check Line 14 in code)
My code's below:
public class AveragerConsole
{
public static void main(String args[])
{
boolean stop = false;
int n = 0;
double x;
double total = 0;
while (stop == false)
{
if (args[n] == "") //Line 14
{
double average = total / (n-1);
System.out.println("Average is equal to: "+average);
stop = true;
}
else
{
x = Double.parseDouble(args[n]);
total = total + x;
n = n + 1;
}
}
}
}
The following error appears:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AveragerConsole.main(AveragerConsole.java:14)
for(String number : args) {
// do something with one argument, your else branch mostly
}
Also, you don't need n, you already have the number of arguments, it's the args length.
This is the simplest way to do it.
For String value comparisons, you must use the equals() method.
if ("".equals(args[n]))
And next, the max valid index in an array is always array.length - 1. If you try to access the array.length index, it'll give you ArrayIndexOutOfBoundsException.
You've got this probably because your if did not evaluate properly, as you used == for String value comparison.
On a side note, I really doubt if this if condition of yours is ever gonna be evaluated, unless you manually enter a blank string after inputting all the numbers.
Change the condition in your while to this and your program seems to be working all fine for n numbers. (#SilviuBurcea's solution seems to be the best since you don't need to keep track of the n yourself)
while (n < args.length)
You gave 3 inputs and array start couting from 0. The array args as per your input is as follows.
args[0] = 1
args[1] = 4
args[2] = 82.4
and
args[3] = // Index out of bound
Better implementation would be like follows
double sum = 0.0;
// No fault tolerant checking implemented
for(String value: args)
sum += Double.parseDouble(value);
double average = sum/args.length;
I'm using this basic and crude code below for calculating prime numbers then exporting them to a text file:
import java.util.Scanner;
import java.io.*;
public class primeGenerator{
public static void main(String[] args)throws Exception {
Scanner kb = new Scanner(System.in);
String prime;
long num = kb.nextLong();
long i;
long z=0;
while(z==0){
for (i=2; i < num ;i++ ){
long n = num%i;
if (n==0){
break;
}
}
if(i == num){
writer(num);
}
num=num+2;
}
}
public static void writer(long num) throws Exception {
FileWriter writer = new FileWriter("prime.txt",true);
String prime= ""+ num;
writer.write(prime);
writer.write(" ");
writer.flush();
writer.close();
}
}
I would like to find primes beyond the Primative long's range and apparently big integer is the way to go about it. So how do i alter my code to do so?
Do you really need this? Having numbers bigger than can be handled by long means you want to test numbers bigger than 9223372036854775807. If your for-loop can test a hundred million divisions per second, it will still take it 2923 years to determine if that number is prime - and longer for larger numbers, of course.
A common optimization is to only test divisions up to sqrt(num). If you haven't found anything then, the number is prime.
Well, use BigInteger wherever you've currently got long. Instead of using % you'll use mod, instead of incrementing you'll use i = i.add(BigInteger.ONE), instead of == 0 you'll use equals(BigInteger.ZERO) etc.
Use Scanner.nextBigInteger instead of Scanner.nextLong, too.
Given that this looks like homework of some description (possibly self-set, of course) I won't write out the whole code for you - but if you have specific problems, feel free to ask.