How can I add up two randomly generated numbers inclusively? Java - java

I'm asking the user to enter two random numbers(i.e 1 10) then I have to add them up inclusively, so (1 10) would be 55.
public int sum(int num1, int num2) {
int counter; //just a variable until I clean this up and get it to work
questions++;
if (num1 < num2) {
int difference = num2-num1;//difference between the given numbers
int holder = 0;
while (holder <= difference) {
holder ++;
num1 += num1;
}
counter = num1;
}
}
This is the chunk of code I have been testing. This gives me 256 when I run 1 and 10.

if (num1 < num2)
{
int answer = num1;
while (num1 <= num2)
{
answer = answer + num1++;
}
retrun answer;
}

Java 8 variant:
IntStream.rangeClosed(Math.min(num1, num2), Math.max(num2, num1)).sum()
What it does:
Create range of ints that contains all numbers from num1 to num2 inclusively
we need to make sure that left border always less than right one, otherwise range will be empty. That's why I've used min() and max()
Add all the numbers together.
Beware though:
Certain combinations of numbers produce a sum that's higher than Integer.MAX_VALUE, and this will cause the sum to overflow and possibly produce negative values.
This can be accounted for by using slightly different version, that's slightly less performant:
IntStream.rangeClosed(Math.min(num1, num2), Math.max(num2, num1))
.mapToObj(BigInteger::valueOf)
.reduce(BigInteger.ZERO, BigInteger::add);

public int sum(int num1, int num2) {
int result = 0;
while(num1<=num2) {
System.out.println("num1 is: "+num1);
result = result + num1;
num1++;
}
return result;
}
Please note the print line within the loop to display the progress of the while.

I'm guessing you're doing this as a programming exercise, so using a loop is the whole point of the task. However, if you just wanted code that gave you the right answer you could use the arithmetic series formula:
public int sum(int num1, int num2) {
if (num1 <= num2) {
return (num2 - num1 + 1) * (num1 + num2) / 2;
}
return 0;
}

Related

Greatest Common Divisor Program Only Printing 1

I'm making a program where you put in two integers, and the program finds the greatest common divisor between the two numbers.
It runs fine, except it prints "1" as the GCD, even when the two numbers should have a different GCD. (Example: 4 & 64. GCD should be 4, but 1 still gets printed.) I can't figure out what's wrong with my code.
For those who want to answer using one method instead, I can't: It's an assignment that requires me to use two different methods in the same program. Please help?
Thanks for reading, and have a good week.
Here my code:
import java.util.Scanner;
public class greatestCommonDivisorMethod {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//Number entry prompts
System.out.print("Please enter first integer: ");
int num1 = input.nextInt();
System.out.print("Please enter second integer: ");
int num2 = input.nextInt();
//Result printed
System.out.println("The greatest common divisor of " +num1+ " and " +num2+ " is " +gcd(num1, num2)+".");
}
public static int gcd(int num1, int num2) {
int gcd = 1;
int k = 2;
while (num1 <= k && k <= num2)
{
if (num1 % k == 0 && num2 % k == 0)
gcd = k;
k++;
}
return gcd;
}
}
while (num1 <= k && k <= num2)
{
if (num1 % k == 0 && num2 % k == 0)
gcd = k;
k++;
}
It looks like you accidentally switched num1 and k in your while loop.
The while condition should probably have k<=num1 instead of num1<=k
Assign your return to a variable then print it
int answer = gcd(num1, num2);
then when printing cast to String or use toString method.
System.out.println("The greatest common divisor of " +answer.toString());

Reorder numbers in a int number to get minimum value

How can I reorder numbers in a int number to get minimum value.
Ex:
I input a number: $71440 and I want my output is: $1447 (this is minimum value after reordering). I think I will spits the numbers in my input number first like this , after that I will reorder them. That is good algorithm?
Yes it is good if you
split by digit
sort digits
make number out of those digits
What you need is essentially a sorting of the digits of the number. So yes, your proposed method will work and it seems as a reasonable practice.
I think this does roughly what you want it to do. Assumes that the input is positive, I'm sure you can figure out how to modify it to work with negative numbers if you need that.
public static int leastValue(int input) {
String s = Integer.toString(input);
char[] c = s.toCharArray();
Arrays.sort(c);
s = new String(c);
return Integer.parseInt(s);
}
The basic idea is:
Turn value into a string
Put each character into an array
Sort the array of characters, in most character sets this will order the numbers from smallest to largest.
Turn it into a string again
Parse it into an int
For readability I think Diasiares answer is better. However a different approach would be something like this. It sorts a long with a "merge sort like" algorithm. To understand how it works please view the gif file from wikipedia
public static long sort(long num) {
long res;
if (num > 9) {
//split num into two parts(n1, n2)
int numberOfDigits = (int) Math.log10(num) + 1;
long n1 = num / (long) Math.pow(10, numberOfDigits / 2);
long n2 = num % (long) Math.pow(10, numberOfDigits / 2);
//sort each part
long s1 = sort(n1);
long s2 = sort(n2);
//merge them into one number
res = merge(s1, s2);
} else {
res = num;
}
return res;
}
/**
* merges two sorted long into on long e.g 149 and 345 will give 134459
*/
public static long merge(long num1, long num2) {
return (num1 == 0 || num2 == 0)
? num1 + num2
: num1 % 10 < num2 % 10
? num2 % 10 + merge(num1, num2 / 10) * 10
: num1 % 10 + merge(num1 / 10, num2) * 10;
}

A persistent compilation error when finding the maximum of three integers using java

I'm new to Java and trying to find a solution to a problem that has been returning a persistent compilation error.
I have pasted my code as below:
import java.util.*;
class MaxInteger {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three integers: ");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int num3 = sc.nextInt();
int max = getMax(num1, num2, num3);
System.out.println("Maximum input integer is " + max);
}
public static int getMax(int num1, int num2, int num3) {
if ((num1 >= num2) && (num1 >= num3))
return num1;
else if ((num2 >= num1) && (num2 >= num3))
return num2;
else if ((num3 >= num1) && (num3 >= num2))
return num3;
}
}
edit: editing this question to make it better after seeing the responses that this may be viewed as off-topic.
The error message I'm getting is "missing return statement".
I understand that there is a Math.max method of finding the maximum, but in this particular case, the task was given to convert to "if else" statements.
There weren't any missing braces, brackets, and parentheses in my original code. They might have occurred in my copying of the code. Apologies for any confusion.
"tl;dr" version:
Sorry for any mistakes, omissions or confusion caused by me.
Math.max() returns the highest from two values. you can apply this operation twice to get max out of three
int max = Math.max(Math.max(num1,num2),num3);
Even though you know that this method will always return something, the compiler doesn't. The solution is to make the last else if an else as you know that this will still be logically correct.
public static int getMax(int num1, int num2, int num3) {
if ((num1 >= num2) && (num1 >= num3))
return num1;
else if ((num2 >= num1) && (num2 >= num3))
return num2;
return num3;
}
And one thing more! You're missing closing bracket of your class which I have added to your code snippet by editing the question as I qualified is as a typo. I assumed that you have it in your original code but I'm not sure now.
The above is about your compilation error. You can find some code review below.
Another thing is DRYing your code. Why should you repeat something that some one has written before? To calculate maximum of three numbers simply return:
public static int maxOfThree(int num1, int num2, int num3) {
return Math.max(Math.max(num1,num2),num3);
}
The reason for your compiler error appears to be that your getMax() method may not return a value in all cases. Change your code to this for immediate relief:
public static int getMax(int num1, int num2, int num3) {
if ((num1 >= num2) && (num1 >= num3))
return num1;
else if ((num2 >= num1) && (num2 >= num3))
return num2;
// otherwise num3 must be the greatest
else return num3;
}
Better yet, use my implementation or the answer given by #Amy for even better results.
Just for fun you could actually determine the max of the three numbers using a single ternary statement:
public static int getMax(int num1, int num2, int num3) {
int max = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3) ? num2 : num3;
return max;
}
With regard to your current compiler error, the problem I saw is that you were missing a closing parenthesis around the class. Your code should take this form:
class MaxInteger {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three integers: ");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int num3 = sc.nextInt();
int max = getMax(num1, num2, num3);
System.out.println("Maximum input integer is " + max);
}
public static int getMax(int num1, int num2, int num3) {
int max = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3) ? num2 : num3;
return max;
}
}
This block:
public static int getMax(int num1, int num2, int num3) {
if ((num1 >= num2) && (num1 >= num3))
return num1;
else if ((num2 >= num1) && (num2 >= num3))
return num2;
else if ((num3 >= num1) && (num3 >= num2))
return num3;
}
Requires an else statement with a return, or a return at the end of if/else block.
In your getMax method, compiler is telling you that you must always return a result. You should add a case which will execute when none of youre if clauses match - add it on the end or under an else block.
How about this solution?
private static int getMax(int a, int b, int c) {
int[] values = new int[]{a, b, c};
Arrays.sort(values);
return values[2];
}
The key point is making your paths easier to "read" by humans. That helps finding out why the compiler has a problem with your source code.
In your case: use braces for blocks. Always, even for one-liners, like in:
public static int getMax(int num1, int num2, int num3) {
if ((num1 >= num2) && (num1 >= num3)) {
return num1;
} else {
if ((num2 >= num1) && (num2 >= num3)) {
return num2;
} else {
if ((num3 >= num1) && (num3 >= num2)) {
return num3;
}
}
}
Of course, many people would say "there is a lot of 'line noise' now"; but the point is: isn't it much more obvious now that your final if ... doesn't have an else? In other words: there is a path through your method that doesn't contain a return statement. And you just didn't see that because of the way you wrote down/formatted/indented your code!
Thus, the key lessons here are:
Learn to read the compiler messages. They are really good in Java, and they are to be trusted!
Structure your code in a way that clearly shows the paths within your methods.
And of course, as others have correctly pointed out: don't re-invent the wheel. Java is coming with a ton of ready-to-use-well-tested libraries. Besides the learning effects, there is no sense in implementing your own min/max functionality.
You can use Collections
public class MaxInteger {
static List<Integer> list = new ArrayList<Integer>();
public static void main(String[] args) {
System.out.print("Enter three integers: ");
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 3; i++) {
list.add(sc.nextInt());
}
Collections.sort(list); // Sort the arraylist
System.out.println("Maximum input integer is " + list.get(list.size() - 1));
}
}
Java 8 solution for finding max from any number of inputs:
public static int maxOf(int... num) {
return Arrays.stream(num).max().getAsInt();
}

Subtracting Random numbers [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I'm making a game where the user must solve a simple subtraction but the result must be a positive whole number. I managed to do everything but for some reason the answer is sometimes negative and I'm not sure how to fix it
import java.util.Random;
import java.util.Scanner;
public class Subtraction {
public static void main(String[] args) {
Random r = new Random();
final int MAX = 10;
// get two random numbers between 1 and MAX
int num1 = r.nextInt(MAX) - 1;
int num2 = r.nextInt(MAX) - 1;
int total = (num1 - num2);
// display a question
System.out.printf("What is your answer to %d - %d = ?%n", num1, num2);
// read in the result
Scanner stdin = new Scanner(System.in);
int ans = stdin.nextInt();
stdin.nextLine();
// give an reply
if (ans == total) {
System.out.println("You are correct!");
} else {
System.out.println("Sorry, wrong answer!");
System.out.printf("The answer is %d + %d = %d%n", num1, num2, (num1 - num2));
}
}
}
Two possible solutions: Just change your total line with a condition to subtract the larger one from the smaller one (unless they're the same, in which case you'll get 0)
int total = (num1 > num2) ? (num1 - num2) : (num2 - num1);
Or just use the absolute value:
int total = java.lang.Math.abs(num1 - num2);
Change the printf as well:
System.out.printf("What is your answer to %d - %d = ?%n", (num1 > num2) ? num1 : num2, (num1 > num2) ? num2 : num1);
The conditionals are just making sure that the bigger number comes before the smaller number, or if they happen to be equal, that they are both listed.
Check out http://www.cafeaulait.org/course/week2/43.html for a more thorough explanation of the ? operator.
Generate your first value with room at the bottom for a second value to be subtracted, and the second one from a range bounded by the first:
int num1 = r.nextInt(MAX - 1) + 2; // produces values from 2 to MAX, inclusive
int num2 = r.nextInt(num1 - 1) + 1; // produces values from 1 to (num1 - 1), inclusive
The first number will always be strictly larger than the second, by construction, so the difference will always be a positive integer.
Well, with two random numbers in the same range, in random order, either cold be larger and the subtraction could be negative. Either fix how you get the numbers, or fix how they are ordered, or fix how you get their difference; any of these will do the job.
The code at the very heart of your program is wrong:
// get two random numbers between 1 and MAX
int num1 = r.nextInt(MAX) - 1;
int num2 = r.nextInt(MAX) - 1;
r.nextInt(MAX) returns a number between 0 (inclusive) and MAX (exclusive). Your code subtracts one from it, so you get a number in the range [−1, MAX−2].
Since you want it to be a simple subtraction where all numbers are in the range [1, MAX], you have to generate them that way. The general form of the subtraction is:
result = num1 − num2
This equation has the following constraints:
1 <= result <= MAX
1 <= num1 <= MAX
1 <= num2 <= MAX
result < MAX, since otherwise num2 would have to be 0
1 < num1, since otherwise the result would become negative
num2 < MAX, since otherwise result would have to be larger than MAX
This leaves the following allowed ranges:
1 <= result <= MAX − 1
2 <= num1 <= MAX
1 <= num2 <= MAX − 1
num2 <= num1 - 1
To generate these numbers, the code has to look like this:
int num1 = randomBetween(2, MAX);
int maxNum2 = Math.min(MAX - 1, num1 - 1);
int num2 = randomBetween(1, maxNum2);
Now what is randomBetween? You have to define it:
randomBetween(min, max) ≡ r.nextInt(max + 1 - min) + min
Together, this is:
int num1 = r.nextInt(MAX + 1 - 2) + 2;
int maxNum2 = Math.min(MAX - 1, num1 - 1);
int num2 = r.nextInt(maxNum2 + 1 - 1) + 1;
int result = num1 - num2;
assert 1 <= result && result <= MAX;
Since you know the result must be positive, I would start with the result
int total = r.nextInt(MAX) + 1;
int num2 = r.nextInt(MAX - total + 1);
int num1 = total + num2;
This way you can be sure that num1 - num2 will always be positive.
package optinalTest;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Subtraction {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
randomNumber();
}
}
private static void randomNumber() {
// get two random numbers between 1 and MAX
int num1 = ThreadLocalRandom.current().nextInt(10000, 9999998);
int num2 = ThreadLocalRandom.current().nextInt(num1 + 1, 9999999);
int total = (num2 - num1);
// display a question
System.out.printf("What is your answer to %d - %d = ?%n", num2, num1);
// read in the result
Scanner stdin = new Scanner(System.in);
int ans = stdin.nextInt();
stdin.nextLine();
// give an reply
if (ans == total) {
System.out.println("You are correct!");
} else {
System.out.println("Sorry, wrong answer!");
System.out.printf("The answer is %d - %d = %d%n", num2, num1, (num2 - num1));
}
}
}

Check if number is in range of Dynamically Changing Numbers?

Is there a way to determine if a number is within a range of two specific numbers, if those numbers are changing? For example:
int num1 = -10;
int num2 = 100;
int num3 = 5;
if(num3 > num 1 && num3 < num2){
}
It would be rather easy to determine whether num3 is in between num1 and num2. However, lets say num1 and num2 change dynamically during the running of the program:
num2 becomes -30
All else remains the same. Now the same algorithm as before would no longer work. Is there an elegant way to check if a number is withing a range using dynamically changing max and min values?
You can try the following, i create 2 more variable iMin & iMax, and before checking num3 is in rank, we define max value and min value:
int num1 = -10;
int num2 = 100;
int num3 = 5;
if (num3 > Math.min(num1, num2) && num3 < Math.max(num1, num2)) {
}
That's kinda silly. If you have an algorithm in a function and you say you want num3 to be between num1 and num2, that's it. That rule shouldn't change, because num1 or num2 changed. The implementation should be generic and independent of the values.
If you need some verification prior to that, do it. I don't a see any other elegant way to do it.

Categories

Resources