I am writing a Monte Carlo Simulation to check the odds of two numbers being co-prime when the two numbers have to be divisible by a certain input. The first number x must be divisible by the first input num1 and vise versa with y and num2. My problem is once I checked that the numbers are divisible and wither they are Co-Primes or not the ratio of amount of times they come back as Co-primes and not Co-primes is not the same as what they should be. For example the ratio of Co-Primes to Non Co-Primes should be 49% when the constraints are 7 and 13 but I get mixed outputs. Sorry if my explanation is not very clear I am not very good at explaining what I mean so I will answer any questions you need for context.
public class MonteCarloCoPrime {
public static void main(String args[] ) throws Exception {
//Initializing Scanner and Random Objects
Scanner scan = new Scanner(System.in);
Random rand = new Random();
//Initializing integers
int num1 = scan.nextInt();
int num2 = scan.nextInt();
int x;
int y;
int positiveResults = 0;
int negativeResults = 0;
//Loops 10000 times with new x and y variables
for(int i = 0;i<100000;i++){
//setting X and Y to random numbers between 1-10000
x = rand.nextInt(10001);
y = rand.nextInt(10001);
//Checking Numbers are divisible by inputs
if(ConditionCheck(x,y,num1,num2)) {
//Checking if Co-Prime
if(coprimeCheck(x,y)) {
positiveResults++;
}
else {
//If Not Co Prime
negativeResults++;
}
}
}
System.out.println("Number of Co-Prime Results: " + positiveResults);
System.out.println("Number of Non Co-Prime Results: " + negativeResults);
scan.close();
}
//Finding Greatest Common Divisor
public static int gcd(int x, int y) {
if(x==y) {
return x;
}
if(x==0 || y==0) {
return 0;
}
if(x > y) {
return gcd(x-y,y);
}
return gcd(x,y-x);
}
//Checking that x is divisible by num1 and y is divisible by num2
public static boolean ConditionCheck(int x,int y,int num1,int num2) {
if(x%num1==0 && y%num2==0) {
return true;
}
else {
return false;
}
}
//Checks if numbers are Co-Prime
public static boolean coprimeCheck(int x, int y) {
if(gcd(x,y)==1) {
return true;
}
else {
return false;
}
}
}
Aucun commentaire:
Enregistrer un commentaire