I wrote this simple code just out of curiosity and encountered some behavior of the nextInt() method from the Java Random class that I don't quite understand. Can anyone help me to figure it out?
The program simulates a simple coin flipping. So as far as I understand the probability of the nextInt(101) for numbers less and greater than 49 should be equal.
But as long as I increase the number of iterations, the balance tends to get positive, for example after 100,000 iterations, I didn't get a negative number. Why does this happen?
public static void main(String[] args) {
int balance = 0;
for (int i = 0; i < 100000; i++) {
Random random = new Random();
int result = random.nextInt(101);
if (result > 49) {
balance++;
} else {
balance--;
}
}
System.out.println("Player's balance = " + balance);
}
You call int result = random.nextInt(101) which creates uniformly distributed integers in [0,100], which can take 101 different values. If you check if (result > 49) then you have 51 possible values ([50,100]) and in the else case you have only 50 values ([0,49]). Thus the result is more likely to be in the upper part. To fix it you can do int result = random.nextInt(100).
you are testing 51 possibilities for a positive outcome and only 50 possibilities for a negative outcome.
100-50 = 51 possibilities
0-49 = 50 possibilities.
If you have tried, random.nextInt(99), result will be different, I got minus value many times.
The reason behind this is that random.nextInt() Method.
quoted from the JavaDoc.
The algorithm is slightly tricky. It rejects values that would result
in an uneven distribution (due to the fact that 2^31 is not divisible
by n). The probability of a value being rejected depends on n. The
worst case is n=2^30+1, for which the probability of a reject is 1/2,
and the expected number of iterations before the loop terminates is 2.
Please see here Random.java#nextInt(int)
Related
Link of the question-https://www.codechef.com/problems/MATPH
So , I'm stuck on this question for hours and I don't know where I'm wrong.
I have used Sieve of Eratosthenes for finding prime and I saved all prime numbers in hash map.Online judge is giving me wrong answer on test cases.
static void dri(int n) {
long large=0;int r=0,x,count=0,p,count1=0;
x=(int)Math.sqrt(n);
//To understand why I calculated x let's take an example
//let n=530 sqrt(530) is 23 so for all the numbers greater than 23 when
//we square them they will come out to be greater than n
//so now I just have to check the numbers till x because numbers
//greater than x will defiantly fail.I think you get
//what I'm trying to explain
while(r<x) {
r = map.get(++count); // Prime numbers will be fetched from map and stored in r
int exp = (int) (Math.log(n) / Math.log(r));
//To explain this line let n=64 and r=3.Now, exp will be equal to 3
//This result implies that for r=3 the 3^exp is the //maximum(less than n) value which I can calculate by having a prime in a power
if (exp != 1) { //This is just to resolve an error dont mind this line
if (map.containsValue(exp) == false) {
//This line implies that when exp is not prime
//So as I need prime number next lines of code will calculate the nearest prime to exp
count1 = exp;
while (!map.containsValue(--count1)) ;
exp = count1;
}
int temp = (int) Math.pow(r, exp);
if (large < temp)
large = temp;
}
}
System.out.println(large);
}
I
For each testcase, output in a single line containing the largest
beautiful number ≤ N. Print −1 if no such number exists.
I believe that 4 is the smallest beautiful number since 2 is the smallest prime number and 2^2 equals 4. N is just required to ≥ 0. So dri(0), dri(1), dri(2) and dri(3) should all print −1. I tried. They don’t. I would believe that this is the reason for your failure on CodeChef.
I am leaving it to yourself to find out how the mentioned calls to your method behave and what to do about it.
As an aside, what’s the point in keeping your prime numbers in a map? Wouldn’t a list or a sorted set be more suitable?
Here, I am finding number of perfect square numbers in given range.
But I am dealing with 'for' loop execution that takes much time for execution.
The index/key traverses from two numbers, lets say A to B, and does some operation in for loop.
The problem arises when there's large difference between A and B (e.g. A = 2 & B = 100000)
Can u suggest how can I reduce or optimize the execution time?
Scanner in = new Scanner(System.in);
int A = in.nextInt();
int B = in.nextInt();
int cnt = 0;
for(int number =A ; number<= B; number++){
int sqrt = (int) Math.sqrt(number);
if(sqrt*sqrt == number) {
cnt++;
}
}
System.out.println(cnt);
Or is it because of Math class operations that takes too much time to execute?
Can you suggest any alternate approach to find the square numbers between given range?
Thanks in advance!
I found an alternate way to find the count of perfect square numbers between given range.
This can be simply achieve by using Math.floor and Math.ceil operations.
Math.floor(Math.sqrt(B)) - Math.ceil(Math.sqrt(A)) + 1
Thanks! :)
Instead of going through each number in the range and figuring out if its a perfect square, I would suggest the below
Find a square root of the start number and find the integer part of it.
Lets say start number is 5. So integer part of the square root will be 2.
Now do the same for the range end number
Lets say end range was 1000, so the integer part of its square root would be 31. Now iterate from 2+1 to 31 and keep printing its square. That would give you the perfect squares between the given range.
Instead of the if(sqrt * sqrt == number) you could also check whether the double returned by Math.srt(number) is a integer. The algorithm would than become as follows:
for(int number =A ; number<= B; number++){
if((Math.sqrt(number) % 1) == 0) {
cnt++;
}
}
Note: Haven't tried the code myself so might not work as I expect.
Regarding the question on how you can improve the performance. The checking on whether the number is perfect could be done in parallel by executing per number a task. The access to the counter has to be synchronized than, (to be on the safe side).
This program is essentially a game where the user must enter numbers to see which numbers are good: numbers with an even number of even digits, and an odd number of odd digits.
So first of all, the program ends when I enter a one digit number, which is not intentional. I assume that has something to do with the while being while (n > 0). There also is likely an issue with the if (numEven % 2 == 0......) because the print results seem almost random, with a number being good and the same number not being good sometimes.
Honestly, I am lost at this point. Thank you so much in advance for any help.
UPDATE: This code is working how I want it to, I just wanted to thank everybody who helped out! It's my first semester of computer science class, so I'm still rather new at this...excuse my mistakes that were likely pretty stupid :)
package quackygame;
import java.util.Scanner;
public class QuackyGame
{
public static void main(String[] args)
{
System.out.println("Welcome to the Number Game!"
+ " Try to figure out the pattern "
+ "in the numbers that Wallace likes!");
Scanner scan = new Scanner (System.in);
int n;
int numEven = 0;
int numOdd = 0;
boolean isEven;
do
{
System.out.print("Enter a number > 0: ");
n = scan.nextInt();
while (n > 0)
{
if (n % 2 == 0)
{
//n is even
isEven = true;
numEven++;
}
else
{
//n is odd
isEven = false;
numOdd++;
}
n /= 10;
}
//if numEven is even and numOdd is odd
if (numEven % 2 == 0 && numOdd % 2 == 1)
System.out.println("Wallace liked your number!");
else
{
System.out.println("Wallace didn't like your number.");
}
numEven = 0;
numOdd = 0;
}
while (n >= 0);
}
}
There are a few core issues in the code based on the desired results that you described. The most glaring issue I see is that you intend for the game to essentially "start from scratch" at the beginning of each round, but you never actually reset the numEven and numOdd variables. This is the source of your print results seeming random. For example, if you started a game and input the number:
34567
The game would process the number and say that it is a favorable number because it is odd, has an odd number of odd digits (3), and has an even number of even digits (2). However, upon playing the game again, it would execute the same code without setting the variables back to 0, which means that upon entering:
34567
The game would process this number as a bad number because the accumulated value of odd digits would be 6 instead of 3 (since 3 the first time + 3 the second time results in 6), and 6 is even. So what we want to do is this:
...
int n;
do
{
int numEven = 0;
int numOdd = 0;
System.out.print("Enter a number: ");
n = scan.nextInt();
...
By placing the numEven and numOdd declarations inside of the "do" block, they are local variables which only exist for the duration of the do block. We could also do something as simple as this:
...
else
{
System.out.println("Wallace didn't like your number.");
}
numEven = 0;
numOdd = 0;
}
while (n > 0);
...
Just resetting the values will help us to keep track of the actual intended values of numOdd and numEven more consistently.
With regard to the program closing when you input a single digit number, I'm not sure. That doesn't make sense because since it is a do-while loop it should at least execute once, and issue one of the print statements. I'm loading this code into my IDE right now to give it a run through. I'll update my answer if I find something.
-EDIT-: Upon reading your question again, it seems that you may not be suggesting that the program closes before actually completing any of its functions, but simply that it closes at all. The reason for the closing of the program is that you are performing an integer division arithmetic function where you probably want to be using a different type of number. Let me explain:
In normal human counting, we have our natural set of numbers which have no decimal points. They usually start like this:
1, 2, 3, 4, 5 ...
Then we have a separate set of numbers for math where we operate with more precision:
0.5, 1.4232, 3.142 ...
When we are talking about numbers with normal human language, we assume that dividing 1 by 2 results in 0.5. However, computers do not implicitly know this. In order for a computer to reach the conclusion "0.5" from the division of 1 by 2, you need to explicitly tell it that it should use a certain type of number to produce that output.
The "normal" numbers I referenced earlier are most loosely related to the integer in programming. It's basically a number without a decimal point. What that means is that whenever you divide two integers together, you always get another integer as the result. So if you were to divide 1 by 2, the computer would not interpret the result as 0.5 because that number has a decimal. Instead, it would round it down to the nearest integer, which in this case is 0.
So for a more specific example referencing the actual question at hand, let's say we input the number 5 into our program. It goes through all of the calculations for odds and evens, but eventually gets to this line:
n /= 10
This is where things get funky. We are dividing two integers, but their result does not come out as a perfect integer. In this case, the result of 5 / 10 is again 0.5. But for the computer, since we are dividing two integers, the result 0.5 just won't do, so after rounding down to the nearest integer we get 0. At this point, there is one fatal mistake:
(while n > 0);
When we perform this check, we get false and the while loop ends. Why? Because after performing n /= 10, n becomes 0. And 0 is not greater than 0.
How can we fix this? The best thing to do is probably just use a floating point number to perform the calculations. In Java, this is pretty easy. All we really have to do is:
n /= 10.0
When Java sees that we are dividing by 10.0, which is not an integer, it automatically converts "n" to a floating point number to divide by 10.0. In this case then, if n is 5, our result in dividing 5 by 10.0 will be 0.5. Then, when we run:
(while n > 0);
This becomes true! And the loop does not break.
I am going to put all of these changes into my IDE just to confirm that everything is working as intended for me. I would suggest you give it a try too to see if it fixes your problems.
Hope this helps.
You are increasing numEven or numOdd count each time you input a number, and then you use if (numEven % 2 == 0 && numOdd % 2 == 1) , it is random because if you put number 33 for the first time => numOdd = 1; => true => "Wallace likes" , but next time you put 33 for the second time => numOdd = 2; => false => "Wallace doesnt like".
Edit* Maybe you wanted something like this?
public static void main(String[] args)
{
System.out.println("Welcome to the Number Game!"
+ " Try to figure out the pattern "
+ "in the numbers that Wallace likes!");
Scanner scan = new Scanner (System.in);
int n;
boolean isEven;
do
{
System.out.print("Enter a number: ");
n = scan.nextInt();
//if 0, you leave the loop
if(n==0) {
System.out.println("You pressed 0, have a nice day");
break;
}
if (n % 2 == 0)
{
//it is even
isEven = true;
}
else
{
//it is not even
isEven = false;
}
//if even then he likes it, otherwise he does not
if (isEven)
System.out.println("Wallace liked your number!");
else
{
System.out.println("Wallace didn't like your number.");
}
}
//put any contition here, lets say if you press 0 , you leave the loop
while (n != 0);
}
All the solutions online I can find use BigInteger but I have to solve this using arrays.
I'm only a beginner and I even took this to my Computer Science club and even couldn't figure it out.
Every time I enter a number greater than 31, the output is always zero.
Also, when I enter a number greater than 12, the output is always incorrect.
E.g. fact(13) returns 1932053504 when it should return 6227020800
Here's what I have so far:
import java.util.Scanner;
class Fact
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter the number you wish to factorial");
int x = kb.nextInt();
System.out.println(fact(x));
}
public static int fact(int x)
{
int[] a = new int[x];
int product = 1;
for(int i = 0; i < a.length; i++)
{
a[i] = x;
x--;
}
for(int i = 0; i < a.length; i++)
{
product = product * a[i];
}
return product;
}
}
Maximum Values Make Large Numbers Terrible
Sadly, because of the maximum values of integers and longs, you are unable to go any larger than
For Longs:
2^63 - 1
9223372036854775807
9 quintillion 223 quadrillion 372 trillion 36 billion 854 million 775 thousand 807
and For Ints:
2^31 - 1
2147483647
2 billion 147 million 483 thousand 647
(I put the written names in to show the size)
At any point in time during the calculation you go over these, "maximum values," you will overflow the variable causing it to behave differently than you would expect, sometimes causing weird zeros to form.
Even BigIntegers have problems with this although it can go up to numbers way higher than just longs and ints which is why they is used with methods that generate massive numbers like factorials.
You seem to want to avoid using BigInteger and only use primatives so long will be the largest data type that you can use.
Even if you convert everything over to long (except the array iterators of course), you will only be able to calculate the factorial up to 20 accurately. Anything over that would overflow the variable. This is because 21! goes over the "maximum value" for longs.
In short, you would need to either use BigInteger or create your own class to calculate the factorials for numbers greater than 20.
I have the following piece of code:
public class Main {
private static final Random rnd = new Random();
private static int getRand(int n) {
return (Math.abs(rnd.nextInt())%n);
}
public static void main(String[] args) {
int count=0, n = 2 * (Integer.MAX_VALUE/3);
for(int i=0; i<1000000; i++) {
if(getRand(n) < n/2) {
count++;
}
}
System.out.print(count);
}
}
This always gives me a number close to 666,666. Meaning two-thirds of the numbers generated are below the lower half of n. Not that this is obtained when n = 2/3 * Integer.MAX_VALUE. 4/7 is another fraction that gives me a similar spread (~5714285). However, I get an even spread if n = Integer.MAX_VALUE or if n = Integer.MAX_VALUE/2. How does this behavior differ with the fraction used. Can somebody throw some light on it.
PS: I got this problem from the book Effective Java by Joshua Bloch.
The problem is in the modulo (%) operator which results in an uneven distribution of numbers.
For example, imagine MAX_INT is 10, and n = 7, the mod operator will map the values 8, 9 and 10 to 1, 2 and 3, respectively. This will result that the numbers 1, 2 and 3 will have double the probability of all other numbers.
One way to solve this is by checking the output of rnd.nextInt() and try again while it's bigger than N.
You would get 50-50 if you kept only values of Math.abs(rnd.nextInt()) in the range of [0..2/3(Integer.MAX_VALUE)]. For the rest 1/3*Integer.MAX_VALUE numbers, due to modulo you will get a smaller number in the range of [0..1/3 Integer.MAX_VALUE].
All in all, numbers in the range of [0..1/3 Integer.MAX_VALUE] have double the chance to appear.
The Random class is designed to generate pseudo-random numbers. That means they are elements of a defined sequence that have an uniform distribution. If you don't know the sequence, they seem to be random.
Having said that, the problem is that you mess up the uniform distribution you get by using the modulus operator. On coding horror, there is a very nice article that explains this issue, although for a slightly different problem. Now, you can find a solution to your problem along with a proof here.
As observed above, getRand does not generate uniformly distributed random numbers over the range [0, n].
In general, suppose that n = a * Integer.MAX_VALUE / b, where a/b > 0.5
For ease of writing, let M = Integer.MAX_VALUE
The Probability Density Function (PDF) of getRand(n) is given by:
PDF(x) = 2/M for 0 < x < (b-a)M/b
= 1/M for (b-a)M/b < x < aM/b
n/2 corresponds to the mid-point of the range [0, aM/b] = aM/2b
Integrating the PDF over the 'first-half' range [0, n/2] we find that the probability (P) that getRand(n) is less than n/2 is given by:
P = a/b
Examples:
a=2, b=3. P = 2/3 = 2/3 = 0.66666... as computed by the questioner.
a=4, b=7. P = 4/7 = 0.5714... close to the questioner's computational result.