Reputation: 62
I want to make a small program to get the desired result by adding two random numbers. For example our desired number is 30 then random no 1 and no 2 should be 15-15, 13-17, 10-20 or anything else. I made this program which shows the sum of random numbers but not desired sum.
import java.util.*;
import java.util.Random;
public class Problem {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random rand = new Random();
Random random = new Random();
int r = rand.nextInt(100) + 1;
int r1 = random.nextInt(100) + 1;
int sum = r + r1;
System.out.println(r + " + " + r1 + " sum is: " + sum);
}
}
Solved it by.
import java.util.*;
import java.util.Random;
public class Problem {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
Random rand= new Random();
Random random= new Random();
int r= rand.nextInt(100)+1;
int n=0;
int sum= sc.nextInt();
n= sum-r;
sum= r+n;
System.out.println(r +" + "+n+ " sum is: " + sum);
}
}
Upvotes: 2
Views: 2377
Reputation: 17
Your problem isn't really in your code; but your logic/math is flawed: you see, when you got three numbers, like
m + n = o
and m is a random number, and o is fixed; then n = o-m.
Thus: you only need one random number, not two!
Upvotes: 0
Reputation: 76
Given the desired number, generate one random number and subtract this from the desired number to get the other random number. The code -
import java.util.*;
import java.util.Random;
import java.util.Scanner;
public class Problem {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int desiredNumber = sc.nextInt();
Random random = new Random();
int r1 = desiredNumber>0?(random.nextInt(desiredNumber)+1):0;
int r2 = desiredNumber - r1;
System.out.println("The desired number is : " + desiredNumber);
System.out.println("The two random numbers are : " + r1 + " and " + r2);
}
}
Upvotes: 1
Reputation: 2330
I think you are looking for this:
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Random rand = new Random();
int r1 = rand.nextInt(n) + 1; // only one random number is needed
int r2 = n-r1; // other will be subtract of n and r1
System.out.println(r1 + " + " + r2 + " sum is: " + n);
Upvotes: 2
Reputation: 140457
Your problem isn't really in your code; but your logic/math is flawed: you see, when you got three numbers, like
m + n = o
and m is a random number, and o is fixed; then n = o-m.
Thus: you only need one random number, not two!
Upvotes: 1
Reputation: 521389
Just choose the first number in the range with an upper limit of the sum, and then retain the second number as the difference of the sum and the first number:
Random rn = new Random();
int max = 30;
int first = rn.nextInt(max) + 1;
int second = max - first;
Now first
and second
are guranteed to sum to the maximum number. I assumed that, for a given sum max
, the smallest number is 1
.
Upvotes: 1