Math.random Scenario - java

Example 1: 50 + (int)(Math.random() * 50) returns an integer between 50 and 99. The maximum number in decimal form being 99.9 recurring.
Example 2:
34 + (int)(Math.random() * 21) returns an integer between 34 and 55.
The maximum number in decimal form being 54.9 recurring.
Why is it that example 2 returns 55 and not 54?

Math.random() returns a decimal in the range of [0.0, 1.0),
So your assumptions are correct in each example
For the first example, 50 + 49.9 = 99.9
For the second example, 34 + 20.9 = 54.9
I am not sure where you are getting 55 for example two because when the decimal is cast to an int, the decimal will lose its precision, effectively rounding it down to create the max of 99 for example 1 and 54 for example 2
Edit
The book is wrong, if you wanted the range to be 34 to 55, the code would have to be
34 + (int)(Math.random() * 22)

I assume this is from a textbook or tutorial? The second example is wrong. It should say "34 to 54", just like you thought it should.

Related

(double)Math.round(dblPerimeter * 100) / 100); why is it times 100 then divide by 100?

I want to know why is that code times perimeter 100 then divide it by 100?
(double)Math.round(dblPerimeter * 100) / 100);
This code would round dblPerimeter to 2 decimal places.
Example on how this works:
Let dblPerimeter = 123.456. Round dblPerimeter to 2 decimals
multiply by 100: 123.456 * 100 = 12345.6
Math.round() 12345.6 to 12346
cast 12346 to (double): 12346.0
divide by 100: 12346.0 / 100 = 123.46
Rounding to the second decimal place. Eventhough you can never be exactly sure with floating-point-arithmetics, but this is what it is supposed to do.

java How to check if math result is measurable?

I would like to check if the result is measurable; that is, whether it has a finite number if decimal places. What do i mean?
double x = 5.0 / 9.0; // x = 0.(5)
x is not measurable.
I want to round x to the second digit ( x = 0.56 ), but in such case:
double x = 1.0 / 8.0; // x = 0.125
I don't want to round anything.
So here is my question. How do i decide if the result can be measured or not?
You cannot. That is the reason, why 1.0 / 3 / 100 * 3 * 100 gives you 0.9999...9. You only have so many bits to represent the numbers. You cannot distinguish between the period
1.0 / 3 and a number that actually has 0.3333.....3 as value
The only fractions which will be exactly represented in a binary will be ones where the denominator is a power of two. If your input is two integers for the numerator and denominator then find the prime factorisation of both and remove the common factors. Then check the only remaining factors on the denominator are power of 2. Say if we want to find 56 / 70 this is 2^3 * 7 / ( 2 * 5 * 7) removing common factors gives 2^2 / 5 so that will not work. But 63 / 72 = (7*3^2) / (2^3 * 3^2) = 7 / 2^3 so will be a terminating binary number
If your working in decimal then powers of 2 and 5 on the denominator will be allowed.

How can I get a random value from 0~600 with an interval of 10?

I have an 600x600 screen that I wanted to divide it each 10 squares basically so I can do an snake game, so I need to generate the food into those divisions.
The code I thought of:
x.nextInt(10)*x.nextInt(6)*x.nextInt(10)
This doesn't work, and even if it worked there are multiple values that can achieve 20, lets say 1*2*10, 2*1*10...
So I also thought of this:
(int)(x.nextInt(600)/10)*10
But it doesn't make the interval of 10...
I also thought of this one:
Integer.parseInt(Double.toString(x.nextInt(600)/10))*10
but its pretty much stupid and it doesn't work (gives an error)
if you didn't understood what I want, here is results:
Random pairs (x and y):
10, 60
420, 170
550, 480
80, 600
Here is what I don't want:
14, 52
88, 19
551, 529
415, 550
How can I manage the logic to make the random with this interval?
You could try:
(int)(Math.random() * 60) * 10
Essentially this finds a random int between 0 and 59 then multiplies it by ten so that the numbers have a gap of 10...
Alternativly, you could take advantage of integer division and use
(int)(Math.random() * 600) / 10 * 10
which works on the same principle.
You can solve this by generating an integer between 0 and 60 (or I guess you really want 0 to 59 as a tile is 10 pixels wide and should be on the screen), and then multiplying that integer by 10.
You should use Math.random()
int random = (int )(Math.random() * 60 +1) * 10;
Description:
random() method returns a random number between 0.0 and 0.999. So, you multiply it by 60, so upper limit becomes 0.0 to 59.999, when you add 1, it becomes 1.0 to 60.999, now when you you truncate to int, you get 1 to 60. and then multiply it by 10 to get a multiple of 10 between 10 to 600.
note: If you want from 0 to 60 remove 1 and use
int random = (int )(Math.random() * 61) * 10;
Have a GridSquare class, with coordinates from 0 to 10 (randomly chosen), and then use a toScreenArea function that multiplies the coordinates by the number of pixels per square to find the appropriate spot on the screen to put the squares on.

Rounding up/down to number

I have a bunch of integers i need to round up or down, to the closest value which divides by 25.
For instance:
417 rounds up to 425
405 rounds down to 400
int roundedValue = (valueToRound + 12) / 25 * 25;
Devide the number by 25, cast it to an integer then multiply it to 25 back
Or Take it's value and remove the result of the value %25
Add 25/2 to the value prior to anything in order to round to the nearest
function roundTo(value, rounding)
{
temp = value + rounding/2;
return temp - temp%rounding;
}

Java Program for Prime numbers

Problem
In this project you will write a Java program that reads a positive integer n from standard input, then
prints out the first n prime numbers. We say that an integer m is divisible by a non-zero integer d if there
exists an integer k such that m = k d , i.e. if d divides evenly into m. Equivalently, m is divisible by d if
the remainder of m upon (integer) division by d is zero. We would also express this by saying that d is a
divisor of m. A positive integer p is called prime if its only positive divisors are 1 and p. The one
exception to this rule is the number 1 itself, which is considered to be non-prime. A positive integer that
is not prime is called composite. Euclid showed that there are infinitely many prime numbers. The prime
and composite sequences begin as follows:
Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, …
Composites: 1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, …
There are many ways to test a number for primality, but perhaps the simplest is to simply do trial
divisions. Begin by dividing m by 2, and if it divides evenly, then m is not prime. Otherwise, divide by 3,
then 4, then 5, etc. If at any point m is found to be divisible by a number d in the range 2 d m−1, then
halt, and conclude that m is composite. Otherwise, conclude that m is prime. A moment’s thought shows
that one need not do any trial divisions by numbers d which are themselves composite. For instance, if a
trial division by 2 fails (i.e. has non-zero remainder, so m is odd), then a trial division by 4, 6, or 8, or any
even number, must also fail. Thus to test a number m for primality, one need only do trial divisions by
prime numbers less than m. Furthermore, it is not necessary to go all the way up to m−1. One need only
do trial divisions of m by primes p in the range 2 p m . To see this, suppose m >1 is composite.
Then there exist positive integers a and b such that 1 < a < m, 1 < b < m, and m = ab . But if both
a > m and b > m , then ab > m, contradicting that m = ab . Hence one of a or b must be less than
or equal to m .
To implement this process in java you will write a function called isPrime() with the following
signature:
static boolean isPrime(int m, int[] P)
This function will return true or false according to whether m is prime or composite. The array
argument P will contain a sufficient number of primes to do the testing. Specifically, at the time
isPrime() is called, array P must contain (at least) all primes p in the range 2 p m . For instance,
to test m = 53 for primality, one must do successive trial divisions by 2, 3, 5, and 7. We go no further
since 11 > 53 . Thus a precondition for the function call isPrime(53, P) is that P[0] = 2 , P[1] = 3 ,
P[2] = 5, and P[3] = 7 . The return value in this case would be true since all these divisions fail.
Similarly to test m =143 , one must do trial divisions by 2, 3, 5, 7, and 11 (since 13 > 143 ). The
precondition for the function call isPrime(143, P) is therefore P[0] = 2 , P[1] = 3 , P[2] = 5, P[3] = 7 ,
and P[4] =11. The return value in this case would be false since 11 divides 143. Function isPrime()
should contain a loop that steps through array P, doing trial divisions. This loop should terminate when
2
either a trial division succeeds, in which case false is returned, or until the next prime in P is greater
than m , in which case true is returned.
Function main() in this project will read the command line argument n, allocate an int array of length n,
fill the array with primes, then print the contents of the array to stdout according to the format described
below. In the context of function main(), we will refer to this array as Primes[]. Thus array Primes[]
plays a dual role in this project. On the one hand, it is used to collect, store, and print the output data. On
the other hand, it is passed to function isPrime() to test new integers for primality. Whenever
isPrime() returns true, the newly discovered prime will be placed at the appropriate position in array
Primes[]. This process works since, as explained above, the primes needed to test an integer m range
only up to m , and all of these primes (and more) will already be stored in array Primes[] when m is
tested. Of course it will be necessary to initialize Primes[0] = 2 manually, then proceed to test 3, 4, …
for primality using function isPrime().
The following is an outline of the steps to be performed in function main().
Check that the user supplied exactly one command line argument which can be interpreted as a
positive integer n. If the command line argument is not a single positive integer, your program
will print a usage message as specified in the examples below, then exit.
Allocate array Primes[] of length n and initialize Primes[0] = 2 .
Enter a loop which will discover subsequent primes and store them as Primes[1] , Primes[2],
Primes[3] , ..., Primes[n −1] . This loop should contain an inner loop which walks through
successive integers and tests them for primality by calling function isPrime() with appropriate
arguments.
Print the contents of array Primes[] to stdout, 10 to a line separated by single spaces. In other
words Primes[0] through Primes[9] will go on line 1, Primes[10] though Primes[19] will go
on line 2, and so on. Note that if n is not a multiple of 10, then the last line of output will contain
fewer than 10 primes.
Your program, which will be called Prime.java, will produce output identical to that of the sample runs
below. (As usual % signifies the unix prompt.)
% java Prime
Usage: java Prime [PositiveInteger]
% java Prime xyz
Usage: java Prime [PositiveInteger]
% java Prime 10 20
Usage: java Prime [PositiveInteger]
% java Prime 75
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379
%
3
As you can see, inappropriate command line argument(s) generate a usage message which is similar to
that of many unix commands. (Try doing the more command with no arguments to see such a message.)
Your program will include a function called Usage() having signature
static void Usage()
that prints this message to stderr, then exits. Thus your program will contain three functions in all:
main(), isPrime(), and Usage(). Each should be preceded by a comment block giving it’s name, a
short description of it’s operation, and any necessary preconditions (such as those for isPrime().) See
examples on the webpage.
Attempted Solution
class Prime {
public static void main(String[] args) {
int num1 = 0;
int num2 = 0;
int num3;
for (num1 = 1; num1 < 101; num1++)
System.out.println(num1);
for (num2 = 1; num2 < 101; num1++)
System.out.println(num2);
num3 = num2 % num1;
if (num3 == 0)
System.out.println("The prime numbers are " + num1);
else
System.out.println("The prime numbers are " + (num1 += 1));
}
}
Ben, it looks like you are attempting something that is far beyond your current capability. Start with some much simpler problems. Talk to your teacher and consider taking a more rudimentary course. You don't appear to understand either what the program is supposed to do, or how to write a program that might satisfy the requirements, and nothing we say here can overcome that - you have to develop more understanding of math and programming. We're happy to help with that, but just writing your program here won't help you, and you are too far away from a solution for suggestions to help. I'm sorry if this sounds harsh; honestly, I mean it constructively. Please stay with it - but start simpler.
Your example solution doesn't really follow the problem's specification at all. You should focus first on writing the static boolean isPrime(int m, int[] P) method. All that method needs to do is:
Iterate over the contents of P
If an element evenly divides m, m is composite -- return false
If an element's square is greater than m, m is prime -- return true. It sounds like from the problem description this won't ever happen, P will only have the primes from 2 to the one just before crossing the sqrt(m) boundary
If all the elements of P have been tested, m is prime -- return true
After that you can write main to make the primes array and build it up using the described loop, and finally do argument checking and implement the static void Usage() function to call if the arguments are invalid

Categories