Below is an example of an algorithm that determines
whether a number is even or odd.
function is_even(number)
if number % 2 == 0 then
return True
otherwise
return False
Write a program that generates 100 random numbers (between 1 and
1000), and keeps a count of how many of those random numbers are
even and how many are odd.
Implement the algorithm above (or your improved version) as a
function, which is used to work out whether each number is odd or
even.
When it’s done, your program must display how many numbers of each
type were generated.
N.B the algorithm given is not particularly efficient. How could we
simplify this to reduce the complexity? Hint: the decision uses
Boolean values (the result of the comparison) to work out what
Boolean value (True/False) to return. Can you reduce the number of
Booleans?
import java.util.*;
public class Main
{
public static void main(String[] args) {
// create instance of Random class
Random rand = new Random();
int rand_int1,i,even,odd,r;
even=odd=0;
// Generate random integers in range 0 to 999
for(i=0;i<100;i++)
{
rand_int1 = rand.nextInt(1000);
r=is_even(rand_int1);//sending the random variable to
function
if(r==1)//if it returns 1 it is even
even++;
else //else it is odd
odd++;
}
System.out.println("Total no.of even numbers are "+even);
//printing the even count
System.out.println("Total no.of odd numbers are "+odd); //printing
the odd count
}
public static int is_even(int n) //function to
determine even or odd
{
if(n%2 == 0) //even
return 1; //returns 1
else //odd
return 0; //returns 0
}
}
Get Answers For Free
Most questions answered within 1 hours.