How to get even/odd random number divisible by first random number - java

I have following code:
quesPart1 = ran.nextInt((numbersBetween - 2) + 1) + 2;
quesPart2 = ran.nextInt((numbersBetween - 2) + 1) + 2;
if(quesPart2 > quesPart1)
{
int placeHolder = quesPart1;
quesPart1 = quesPart2;
quesPart2 = placeHolder;
}
//if first part is even
if(quesPart1 % 2 == 0)
{
if(quesPart2 % 2 != 0)
{
--quesPart2;
}
}
else
{
if(quesPart2 % 2 == 0)
{
++quesPart2;
}
}
Above code make sure that if quesPart1 is greater than quesPart2 and both are even or both are odd numbers. Now i want to get only random numbers which are also divisible by one another. Like if i divide quesPart1 by quesPart2 i get integer not decimal number. Any ideas how i can do that without adding too much complexity to above code.

You can do something like:
int div = quesPart1 / quesPart2;
quesPart1 = div * quesPart2;
add this code at the bottom of your code.

Like if i divide quesPart1 by quesPart2 i get integer not decimal number.
Keep it simple: generate random numbers and take their product. Example:
quesPart2 = ran.nextInt(UPPER_BOUND);
int temp = ran.nextInt(UPPER_BOUND);
questPart1 = temp * quesPart2;
Specifying the range, as in the original question, is left an an exercise to the reader. (What, you didn't think I was going to do all the thinking for you, did you? ;-)

Look into the modulus operator, a % b. It returns the left over amount when a is divided by b. When b cleanly divides into a, such that there is no decimal part, a % b will be zero.
In order to generate a number that is divisible by another, given two random numbers, a and b, simply multiply a by b. This will give you c, a number that is a multiple of both a and b, and therefore dividable by both cleanly without remainder.

I have come up with this simple function and a do while loop that is easy to implement.
// This is a simple function to set the min and max integers you want
const getRandomIntInclusive = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
//Define some variables variables
let firstNo = 0
let secondNo = 0
let isDivisible = 0;
//generate random ints until first number is divisible to second number
do {
//get random int between 1-9 for the first and second integer
firstNo = getRandomIntInclusive(1, 9)
secondNo = getRandomIntInclusive(1, 9)
isDivisible = firstNo % secondNo; //Check if it's fully divisible
}
while (isDivisible != 0) //Run until it is fully divisible

To generate Random numbers in java you can use ran.nextInt() or please refer to this link to see how to generate random numbers.
store those 2 random numbers (as num1 and num2).
To verify whether the solution after dividing num1 and num2 is integer or not, use this method:
sol = num1 / num2
if (sol == (int)sol)
{
... //true if the solution is an integer
}

Related

How do I find perfect square from a set of numbers in Java?

So I'm trying to find out the perfect squares within a set of numbers. I declared the necessary variables, added a for loop, added a sqroot = Math.sqrt(num) and a print method to list the numbers. What I can't figure out is how can I make the program pick out the perfect squares within the range of numbers, and find the average of them?
This is for an assignment I'm working on for a class and I've been stuck on this for a while now. I'm also rather new to Java so sorry if this is a stupid question. The code is below:
public class Test {
public static void main(String[] args) {
int num;
double sqroot = 0;
int sumPsq = 0; //sum variable
int psq = 0; //counter for perfect squares
double avg = 0;
for(num = 101; num <= 149; num += 2){
sqroot = Math.sqrt(num);
if(sqroot*sqroot == num){ //Condition to find perfect squares
psq += 1; //counting perfect squares
sumPsq = sumPsq + num; //Find the sum of all the perfect squares
System.out.println(num); //Print out the perfect squares
}
}
avg = 1.0 * sumPsq/psq;
System.out.println(avg);
}
}
This is just a piece of the code from the entire assignment, so if you need more of it then I'm more than willing to provide it. Thanks!
A perfect square is a number that can be expressed as the product of two equal integers so it must be an int after the sqrt. If you do a sqroot*sqroot == num you are just checking that sqrt is working correctly. Some number won't pass the check because of this but usually, you will get way more numbers than you want.
So what you need to do is just checking that after the sqrt the result is an int:
if (sqrootd % 1 == 0) { ... }
An optimization you can do is to check the number is an integer before sqrt.
 
Other than that, your code looks fine to me
I used the following mathematical formula to find the perfect square:
1 + 3 + 5 + 7 .... = n ^ 2
for example: 1 + 3 + 5 = 9 = 3 ^ 2
and sample code:
int i = 1;
while (num > 0) {
num = num - i;
i = i + 2;
}
return num == 0;
The best way to check if square root is an integer you will need below condition
if ((sqroot - Math.floor(sqroot)) == 0){
instead of
if(sqroot*sqroot == num){
The Math.sqrt() method finds the square root of the given number and the floor() method finds the largest (closest to positive infinity) floating-point value that less than or equal to the argument (here square root value returned by sqrt() method) and is equal to a mathematical integer.
Then we calculate the difference between these two to check if the difference is zero. For a perfect square number this difference is always zero. The reason is: square root of perfect square number is integer.
reference

Generating random numbers that are twice as likely to put out even numbers

I'm wondering if there was a way to create a random number generator that generates a number between two integers, but is twice as likely to generate an even number than an odd number. At current, I haven't come up with a way that's even similar or close to 2x as likely.
Simple but should work:
store random float call (0.0f - 1.0f) (random.nextFloat())
get a random integer in desired range
if random float call was less than 0.67f, if needed decrement or increment the random integer to make it even, return value
else, if needed decrement or increment the random integer to make it odd, return value
Make sure you decrement or increment towards the right direction if random integer is a boundary value of the desired range.
There are many ways you could do this. One would be to generate two integers: one between the user's bounds, and one between 0 and 2, inclusive. Replace the last bit of the first number with the last bit of the second number to get a result that is even twice as often as it is odd.
You do need to watch out for the possibility that the bit-twiddling last step puts the result out of bounds; in that event, you should re-draw from the beginning.
Implementing #SteveKuo 's suggestion in the comments:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the minimum number that can be generated: ");
int min = scanner.nextInt();
System.out.print("Please enter the maximum number that can be generated: ");
int max = scanner.nextInt();
int evenOrOdd = 0 + (int)(Math.random() * ((2 - 0) + 1));
int random = 0;
if(evenOrOdd == 2) { // generate random odd number
if(max % 2 == 0) { --max; }
if(min % 2 == 0) { ++min; }
random = min + 2*(int)(Math.random() * ((max - min)/2+1));
} else { //get random number between [(min+1)/2, max/2] and multiply by 2 to get random even number between min and max
random = ((min+1)/2 + (int)(Math.random() * ((max/2 - (min+1)/2) + 1))) * 2;
}
System.out.printf("The generated random number is: %d", random);
}
}
Try it here!

Sum the first N numbers in java

Hello, I am new to programming and I am trying to write a small program where it will calculate the sum for first N numbers. The problem is it does not work for even numbers. I have not managed to figure out why.
My code is as follow:
int n = Integer.parseInt(args[0]);
int sum = (1+n)/2*n;
System.out.println(sum + " is the sum of first " + n + " numbers");
It doesn't work for even n because (n+1)/2 is truncated to an int.
This means that if, for example, n=4, (n+1)/2 results in 2 instead of 2.5, so when you multiply it by n, you get 8 instead of the desired 10.
You can overcome this problem simply by changing the order of the operations. If you first multiply n by (n+1), the result is guaranteed to be even, so dividing it by 2 will produce the correct answer.
int sum = n*(1+n)/2;
You have integer division with (1+n)/2. If your number is even, then (1+n) is odd and the division by 2 will truncate any decimal result, so that an int divided by an int is still an int.
Multiply by n first, then divide by 2. This ensures that the product is even before dividing, so the result is correct.
int sum = (1+n) * n / 2;
One can use ((n * (n + 1)) / 2). But I think the following will work without overflow errors for a few additional values of n:
if ((n & 1) == 0) {
sum = ((n >> 1) * (n + 1));
} else {
sum = (n * ((n + 1) >> 1));
}

Problems Generating A Math.random Number, Either 0 or 1

I want a random number, either 0 or 1 and then that will be returned to main() as in my code below.
import java.util.Scanner;
public class Exercise8Lab7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numFlips = 0;
int heads = 0;
int tails = 0;
String answer;
System.out.print("Please Enter The Number Of Coin Tosses You Want: ");
numFlips = input.nextInt();
for(int x = 1;x <= numFlips; x++){
if(coinToss() == 1){
answer = "Tails";
tails++;
}
else{
answer = "Heads";
heads++;
}
System.out.print("\nCoin Toss " + x + ": " + answer);
}
System.out.println("\n\n====== Overall Results ======" +
"\nPercentage Of Heads: " + (heads/numFlips)*100 + "\nPercentage Of Tails: " + (tails/numFlips)*100);
}
public static int coinToss(){
double rAsFloat = 1 * (2 + Math.random( ) );
int r = (int)rAsFloat;
return r;
}
}
Many solutions had been suggested to use the util.Random option which I have done and works perfectly but I want to sort out why I can't get this to work. Obviously I want the number to be an int myself so I convert it to an int after the random number has been generated. But no matter what I add or multiply the Math.random() by, it will always all either be Heads or all either be Tails. Never mixed.
Try this) It will generate number 0 or 1
Math.round( Math.random() ) ;
You could use boolean values of 0 or 1 based on value of Math.random() as a double between 0.0 and 1.0 and make the random generator much simpler. And you can get rid completely of the coinToss() method.
if(Math.random() < 0.5) {
answer = "Tails";
tails++;
}
Remove the coin toss method and replace the first conditional with the code above.
Math.random(); by itself will return a value between 0.0 and less than 1.0. If the value is in the lower half, [0.0, 0.5), then it has the same probability of being in the upper half, [0.5, 1.0). Therefore you can set any value in the lower half as true and upper as false.
Wierd that no one is using a modulo division for the random number.
This is the simplest implementation you can get:
Random rand = new Random();
int randomValue = rand.nextInt() % 2;
Math.round(Math.random()) will return either 0.0 and 1.0. Since both these values are well within the limits of int range they can be casted to int.
public static int coinToss(){
return (int)Math.round(Math.random());
}
(int)(Math.random()*2) also works fine in this case
its not working because of the integer math you are using, the call to 2+ Math.Random is pretty much always giving you a answer between 0.0 and 1.0.
so assuming that you recieve 0.25 as your result your maths is as follows
double d = 1* (2 + 0.25); // (result = 2
Then you are checking to see if your result == 1 ( which it never will. )
A better result would be to declare java.util.Random as a class variable and call random.nextBoolean() and simply perform your heads/tails calculation on that.
If you were to continue to use Math.random() and lets say
return Math.random() < 0.5
Your results would be ever so slightly skewed due to the fact that Math.random() cannot return 1.0, due to the fact that the java API specification states:
"Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0."
Math.random() returns a random float in the range [0.0,1.0)--that means the result can be anything from 0 up to but not including 1.0.
Your code
double rAsFloat = 1 * (2 + Math.random( ) );
will take this number in the [0.0,1.0) range; adding 2 to it gives you a number in the [2.0,3.0) range; multiplying it by 1 does nothing useful; then, when you truncate it to an integer, the result is always 2.
To get integers from this kind of random function, you need to figure out how many different integers you could return, then multiply your random number by that. If you want a "0 or 1" answer, your range is 2 different integers, so multiply Math.random() by 2:
double rAsFloat = 2 * Math.random();
This gives you a random number in the range [0.0,2.0), which can then be 0 or 1 when you truncate to an integer with (int). If, instead, you wanted something that returns 1 or 2, for example, you'd just add 1 to it:
double rAsFloat = 1 + 2 * Math.random();
I think you've already figured out that the Random class gives you what you want a lot more easily. I've decided to explain all this anyway, because someday you might work on a legacy system in some old language where you really do need to work with a [0.0,1.0) random value. (OK, maybe that's not too likely any more, but who knows.)
The problem can be translated to boolean generation as follow :
public static byte get0Or1 {
Random random = new Random();
boolean res= random.nextBoolean();
if(res)return 1;
else return 0;
}
Here it the easiest way I found without using java.util.Random.
Blockquote
Scanner input = new Scanner (System.in);
System.out.println("Please enter 0 for heads or 1 for tails");
int integer = input.nextInt();
input.close();
int random = (int) (Math.random() + 0.5);
if (random == integer) {
System.out.println("correct");
}
else {
System.out.println("incorrect");
}
System.out.println(random);
This will take a random double from (0 to .99) and add .5 to make it (.5 to 1.49). It will also cast it to an int, which will make it (0 to 1). The last line is for testing.
for(int i=0;i<100;i++){
System.out.println(((int)(i*Math.random())%2));
}
use mod it will help you!
One more variant
rand.nextInt(2);
As it described in docs it will return random int value between 0 (inclusive) and the specified value (exclusive)

Java recursion and integer double digit

I'm trying to take an integer as a parameter and then use recursion to double each digit in the integer.
For example doubleDigit(3487) would return 33448877.
I'm stuck because I can't figure out how I would read each number in the digit I guess.
To do this using recursion, use the modulus operator (%), dividing by 10 each time and accumulating your resulting string backwards, until you reach the base case (0), where there's nothing left to divide by. In the base case, you just return an empty string.
String doubleDigit(Integer digit) {
if (digit == 0) {
return "";
} else {
Integer thisDigit = digit % 10;
Integer remainingDigits = (digit - thisDigit) / 10;
return doubleDigit(remainingDigits) + thisDigit.toString() + thisDigit.toString();
}
}
If you're looking for a solution which returns an long instead of a String, you can use the following solution below (very similar to Chris', with the assumption of 0 as the base case):
long doubleDigit(long amt) {
if (amt == 0) return 0;
return doubleDigit(amt / 10) * 100 + (amt % 10) * 10 + amt % 10;
}
The function is of course limited by the maximum size of a long in Java.
I did the same question when doing Building Java Programs. Here is my solution which works for negative and positive numbers (and returns 0 for 0).
public static int doubleDigits(int n) {
if (n == 0) {
return 0;
} else {
int lastDigit = n % 10;
return 100 * doubleDigits(n / 10) + 10 * lastDigit + lastDigit;
}
There's no need to use recursion here.
I'm no longer a java guy, but an approximation of the algorithm I might use is this (works in C#, should translate directly to java):
int number = 3487;
int output = 0;
int shift = 1;
while (number > 0) {
int digit = number % 10; // get the least-significant digit
output += ((digit*10) + digit) * shift; // double it, shift it, add it to output
number /= 10; // move to the next digit
shift *= 100; // increase the amount we shift by two digits
}
This solution should work, but now that I've gone to the trouble of writing it, I realise that it is probably clearer to just convert the number to a string and manipulate that. Of course, that will be slower, but you almost certainly don't care about such a small speed difference :)
Edit:
Ok, so you have to use recursion. You already accepted a perfectly fine answer, but here's mine :)
private static long DoubleDigit(long input) {
if (input == 0) return 0; // don't recurse forever!
long digit = input % 10; // extract right-most digit
long doubled = (digit * 10) + digit; // "double" it
long remaining = input / 10; // extract the other digits
return doubled + 100*DoubleDigit(remaining); // recurse to get the result
}
Note I switched to long so it works with a few more digits.
You could get the String.valueOf(doubleDigit) representation of the given integer, then work with Commons StringUtils (easiest, in my opinion) to manipulate the String.
If you need to return another numeric value at that point (as opposed to the newly created/manipulated string) you can just do Integer.valueOf(yourString) or something like that.

Categories