This is more of a basic math/programming question. I need to generate a division a/b=c. I will give the user a and b and he has to answer c, but c can only have one decimal. For example, c=5.2 is okay but 5.23 is too much to ask, because the users are children. So I need an algorithm that can generate randomly a division of this kind from all possible combinations where a has to be less than x, b has to be less than y, and c can only have one decimal. Also, a and b have to be integers.
I'm looking for a more elegant solution than trying numbers and checking them until a right combinations is produced. Also, this is for web content, so I'd prefer to do it with javascript, but it can be done in php if necesary. ¿Does some one know how could I do it? I'm not that good at maths.
Thank you very much in advance.
Try generate C
as int/10
.
Then generate B
:
(10 * C) % 10 == 0
int * 2
if (10 * C) % 5 == 0
int * 5
if (10 * C) % 2 == 0
int * 10
elseThen A = B * C
and it is int
PseudoCode:
tenC = rnd();
if(tenC % 10 == 0) B = rnd();
elseif(tenC % 5 == 0) B = rnd() * 2;
elseif(tenC % 2 == 0) B = rnd() * 5;
else B = rnd() * 10;
C = tenC / 10.0;
A = tenC * B / 10;
where rnd() generates integer as you like
Basically we create a list with all of A * 10's prime factors, and then choose a random combination of factors to create B.
int[] primes = new int[] { 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, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 };
List<int> factors = new List<int>();
int x = 1000;
int y = 650;
Random rand = new Random();
int a = rand.Next(x);
int _a = a * 10;
int currentPrime = 0;
//find all factors of a * 10
while (_a > 1)
{
while (_a % primes[currentPrime] == 0)
{
factors.Add(primes[currentPrime]);
_a /= primes[currentPrime];
}
currentPrime++;
}
int b = 1;
foreach(int factor in factors)
{
if (b * factor > y) break;
if (rand.Next(2) == 0)
{
b *= factor;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With