I need random numbers from 1 to 9 (without 0).
//numbers 0 to 9
int iRand = rand() % 10;
But I need 1 to 9.
Thanks.
Just this:
int iRand = (rand() % 9) + 1;
Well, you know how to get a random integer in the range [0, x], right? That's:
rand() % (x + 1)
In your case, you've set x to 9, giving you rand() % 10. So how can you manipulate a range to get to 1-9? Well, since 0 is the minimum value coming out of this random number generator scheme, we know we'll need to add one to have a minimum of one:
rand() % (x + 1) + 1
Now you get the range [1, x + 1]. If that's suppose to be [1, 9], then x must be 8, giving:
rand() % 9 + 1
That's how you should think about these things.
Try:
int iRand = 1 + rand() % 9;
It works by taking a random number from 0 to 8, then adding one to it (though I wrote those operations in the opposite order in the code -- which you do first comes down to personal preference).
Note that % has higher precedence than +, so parentheses aren't necessary (but may improve readability).
To initialize the random number generator call srand(time(0)); Then, to set the integer x to a value between low (inclusive) and high (exclusive):
int x = int(floor(rand() / (RAND_MAX + 1.0) * (high-low) + low));
The floor() is not necessary if high and low are both non-negative.
Using modulus (%) for random numbers is not advisable, as you don't tend to get much variation in the low-order bits so you'll find a very weak distribution.
How about
int iRand = (rand() % 9) + 1;
doh beaten by seconds
Regardless that the answer is picked, modulo based ranging is biased. You can find that all over the internet. So if you really care about that then you have to do a bit more than that (assume arc4random() return a 4 byte integer):
#define NUMBER 9.0
#define RANDOM() (((int)(arc4random() / (float)0xffffffff * (float)NUMBER) + 1) % (NUMBER + 1))
I leave it to you to figure out the correct syntax since you sound like a quite capable developer.
Related
x + (rand() % y - x + 1) this is a formula to find a random number between x and y but I don't know how it was made I want a logical/mathematical explanation for it and thank you in advance.
First, your code should be corrected to x + (rand() % (y - x + 1))
The rand function generates a pseudo random positive integer between 0 and RAND_MAX which is typically implemented by PMMLCG algorithm by Hutchinson. When we assume RAND_MAX is large enough, then the occurrence possibilities of any positive integer are the same. And so, when you apply the result to a mod operation, let's say, %n, then we will have a pseudo random integer in the interval [0, n-1]
In your example, (rand() % (y - x + 1)) generates a pseudo random integer between [0, y-x] and when we add x on it, we get a pseudo random between [x, y]
However, as a supplement, this algorithm has what I would describe as severe problems, the most obvious of which is it relies on the value of RAND_MAX. The standard only guarantee that it's a integer not less than 32767, which is a very small value and so it can contribute to the unevenness of the occurrence possibility of the candidates in the interval.
I suggest you learn to use <random> library in C++11:https://en.cppreference.com/w/cpp/header/random
My output is 20 random 1's, not between 10 and 1, can anyone explain why this is happening?
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand((unsigned)time(0));
int random_integer;
int lowest=1, highest=10;
int range=(highest-lowest)+1;
for(int index=0; index<20; index++){
random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0));
cout << random_integer << endl;
}
}
output:
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
Because, on your platform, RAND_MAX == INT_MAX.
The expression range*rand() can never take on a value greater than INT_MAX. If the mathematical expression is greater than INT_MAX, then integer overflow reduces it to a number between INT_MIN and INT_MAX. Dividing that by RAND_MAX will always yield zero.
Try this expression:
random_integer = lowest+int(range*(rand()/(RAND_MAX + 1.0)))
It's much easier to use the <random> library correctly than rand (assuming you're familiar enough with C++ that the syntax doesn't throw you).
#include <random>
#include <iostream>
int main() {
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937 eng(seed);
std::uniform_int_distribution<> dist(1, 10);
for(int i = 0; i < 20; ++i)
std::cout << dist(eng) << " ";
}
random_integer = (rand() % 10) + 1
That should give you a pseudo-random number between 1 & 10.
A somewhat late answer, but it should provide some additional
information if the quality of the generation is important. (Not all
applications need this—a slight bias is often not a problem.)
First, of course, the problem in the original code is the fact that
range * rand() has precedence over the following division, and is done
using integer arithmetic. Depending on RAND_MAX, this can easily
result in overflow, with implementation defined results; on all
implementations that I know, if it does result in overflow (because
RAND_MAX > INT_MAX / range, the actual results will almost certainly
be smaller than RAND_MAX + 1.0, and the division will result in a
value less than 1.0. There are several ways of avoiding this: the
simplest and most reliable is simply rand() % range + lowest.
Note that this supposes that rand() is of reasonable quality. Many
earlier implementations weren't, and I've seen at least one where
rand() % 6 + 1 to simulate a dice throw alternated odd and even. The
only correct solution here is to get a better implementation of
rand(); it has lead to people trying alternative solutions, such as
(range * (rand() / (RAND_MAX + 1.0))) + lowest. This masks the
problem, but it won't change a bad generator into a good one.
A second issue, if the quality of the generation is important, is
that when generating random integers, you're discretizing: if you're
simulating the throw of a die, for example, you have six possible
values, which you want to occur with equal probability. The random
generator will generate RAND_MAX + 1 different values, with equal
probability. If RAND_MAX + 1 is not a multiple of 6, there's no
possible way of distributing the values equaly amont the 6 desired
values. Imagine the simple case where RAND_MAX + 1 is 10. Using the
% method above, the values 1–4 are twice as likely as the the
values 5 and 6. If you use the more complicated formula 1 + int(6 *
(rand() / (RAND_MAX + 1.0))) (in the case where RAND_MAX + 1 == 10,
it turns out that 3 and 6 are only half as likely as the other values.
Mathematically, there's simply no way of distributing 10 different
values into 6 slots with an equal number of elements in each slot.
Of course, RAND_MAX will always be considerably larger than 10, and
the bias introduced will be considerably less; if the range is
significantly less than RAND_MAX, it could be acceptable. If it's
not, however, the usual procedure is something like:
int limit = (RAND_MAX + 1LL) - (RAND_MAX + 1LL) % range;
// 1LL will prevent overflow on most machines.
int result = rand();
while ( result >= limit ) {
result = rand();
}
return result % range + lowest;
(There are several ways of determining the values to throw out. This
happens to be the one I use, but I remember Andy Koenig using something
completely different—but which resulted in the same values being
thrown out in the end.)
Note that most of the time, you won't enter the loop; the worst case is
when range is (RAND_MAX + 1) / 2 + 1, in which case, you'll still
average just under one time through the loop.
Note that these comments only apply when you need a fixed number of
discrete results. For the (other) common case of generating a random
floating point number in the range of [0,1), rand() / (RAND_MAX +
1.0) is about as good as you're going to get.
Visual studio 2008 has no trouble with that program at all and happily generates a swathe of random numbers.
What I would be careful of is the /(RAND_MAX +1.0) as this will likely fall foul of integer problems and end up with a big fat zero.
Cast to double before dividing and then cast back to int afterwards
I suggest you replace rand()/(RAND_MAX + 1.0) with range*double(rand())/(RAND_MAX + 1.0)). Since my solution seems to give headaches ...
possible combinations of arguments:
range*rand() is an integer and overflows.
double(range*rand()) overflows before you convert it to double.
range*double(rand()) is not overflowing and yields expected results.
My original post had two braces but they did not change anything (results are the same).
(rand() % highest) + lowest + 1
Probably "10 * rand()" is smaller than "RAND_MAX + 1.0", so the value of your calculation is 0.
You are generating a random number (ie (range*rand()/(RAND_MAX + 1.0))) whose value is between -1 and 1 (]-1,1[) and then casting it to an integer. The integer value of such number is always 0 so you end up with the lower + 0
EDIT: added the formula to make my answer clearer
What about using a condition to check if the last number is the same as the current one? If the condition is met then generate another random number. This solution works but it will take more time though.
It is one of the simplest logics, got it from a blog. in this logic you can limit the random numbers with that given modulus(%) operator inside the for loop, its just a copy and paste from that blog, but any way check it out:
// random numbers generation in C++ using builtin functions
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
#include <cstdlib> // contains function prototype for rand
int main()
{
// loop 20 times
for ( int counter = 1; counter <= 20; counter++ ) {
// pick random number from 1 to 6 and output it
cout << setw( 10 ) << ( 1 + rand() % 6 );
// if counter divisible by 5, begin new line of output
if ( counter % 5 == 0 )
cout << endl;
}
return 0; // indicates successful termination
} // end main
- See more at: http://www.programmingtunes.com/generation-of-random-numbers-c/#sthash.BTZoT5ot.dpuf
just wondering, if I have the following code:
int randomNum = rand() % 18 + (-9);
will this create a random number from -9 to 9?
No, it won't. You're looking for:
int randomNum = rand() % 19 + (-9);
There are 19 distinct integers between -9 and +9 (including both), but rand() % 18 only gives 18 possibilities. This is why you need to use rand() % 19.
Do not forget the new C++11 pseudo-random functionality, could be an option if your compiler already supports it.
Pseudo-code:
std::mt19937 gen(someSeed);
std::uniform_int_distribution<int> dis(-9, 9);
int myNumber = dis(gen)
Your code returns number between (0-9 and 17-9) = (-9 and 8).
For your information
rand() % N;
returns number between 0 and N-1 :)
The right code is
rand() % 19 + (-9);
You are right in that there are 18 counting numbers between -9 and 9 (inclusive).
But the computer uses integers (the Z set) which includes zero, which makes it 19 numbers.
Minimum ratio you get from rand() over RAND_MAX is 0, so you need to subtract 9 to get to -9.
The information below is deprecated. It is not in manpages aymore. I also recommend using modern C++ for this task.
Also, manpage for the rand function quotes:
"If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in
j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
and never by anything resembling
j = 1 + (rand() % 10);
(which uses lower-order bits)."
So in your case this would be:
int n= -9+ int((2* 9+ 1)* 1.* rand()/ (RAND_MAX+ 1.));
Anytime you have doubts, you can run a loop that gets 100 million random numbers with your original algorithm, get the lowest and highest values and see what happens.
i am not quite sure how this function in c++ works:
int rand_0toN1(int n) {
return rand() % n;
}
Another tutorial on internet says to get a random number between a range you need to do something different however, with a being first number in range and n is number of terms in range:
int number = a + rand( ) % n;
I have read that it is supposed to return a random number between the value of 0 and n-1, but how does it do that? I understand that % means divide and give the remainder (so 5 % 2 would be 1) but how does that end up giving a number between 0 and n-1? Thanks for help in understanding this. I guess i don't understand what the rand() function returns.
The modulo (remainder) of division by n > 0 is always in the range [0, n); that's a basic property of modular arithmetic.
a + rand() % n does not return a number in the range [0, n) unless a=0; it returns an int in the range [a, n + a).
Note that this trick does not in general return uniformly distributed integers.
rand returns a pseudorandom value bewtween 0 and RAND_MAX, which is usually 32767.
The modulo operator is useful for "wrapping around" values:
0 % 5 == 0
1 % 5 == 1
2 % 5 == 2
3 % 5 == 3
4 % 5 == 4
5 % 5 == 0 // oh dear!
6 % 1 == 1
// etc...
As such, by combining that pseudorandom value with a modulo, you're getting a pseudorandom value that's guaranteed to be between 0 and n - 1 inclusive.
According to your own example, you seems to understand how it works.
rand() just returns an integer pseudorandom number between 0 and RAND_MAX, then you apply the modulo operator to that number. Since the modulo operator returns the remainder of division of one number by another, a number divided by N will always return a number lesser than N.
The rand() function returns an integral value in the interval
[0...RAND_MAX]. And the results of x % n will always be in the
range [0...n) (provided x >= 0, at least); this is basic math.
Please take a look here :
http://www.cplusplus.com/reference/clibrary/cstdlib/srand/
Usually you "seed" it with the time function. And then use the modulus operator to specify a range.
The c++ rand() function gives you a number from 0 to RAND_MAX (a constant defined in <cstdlib>), which is at least 32767. (from the c++ documentation)
The modulus (%) operator gives the remainder after dividing. When you use it with rand() you are using it to set an upper limit (n) on what the random number can be.
For example, lets say you wanted a number between 0 and 4. Calling rand() will give you an answer between 0 and 32767. rand() % 5, however, will force the remainder to be 0, 1, 2, 3, or 4 depending on the value rand() returned (if rand() returned 10, 10%5 = 0; if it returned 11, 11%5 = 0, etc.).
I have to check, if given number is divisible by 7, which is usualy done just by doing something like n % 7 == 0, but the problem is, that given number can have up to 100000000, which doesn't fit even in long long.
Another constrain is, that I have only few kilobytes of memory available, so I can't use an array.
I'm expecting the number to be on stdin and output to be 1/0.
This is an example
34123461273648125348912534981264376128345812354821354127346821354982135418235489162345891724592183459321864592158
0
It should be possible to do using only about 7 integer variables and cin.get(). It should be also done using only standard libraries.
you can use a known rule about division by 7 that says:
group each 3 digits together starting from the right and start subtracting and adding them alternativly, the divisibility of the result by 7 is the same as the original number:
ex.:
testing 341234612736481253489125349812643761283458123548213541273468213
549821354182354891623458917245921834593218645921580
(580-921+645-218+593-834+921-245+917-458+623-891+354-182
+354-821+549-213+468-273+541-213+548-123+458-283+761-643
+812-349+125-489+253-481+736-612+234-341
= 1882 )
% 7 != 0 --> NOK!
there are other alternatives to this rule, all easy to implement.
Think about how you do division on paper. You look at the first digit or two, and write down the nearest multiple of seven, carry down the remainder, and so on. You can do that on any abritrary length number because you don't have to load the whole number into memory.
Most of the divisibility by seven rules work on a digit level, so you should have no problem applying them on your string.
You can compute the value of the number modulo 7.
That is, for each digit d and value n so far compute n = (10 * n + d) % 7.
This has the advantage of working independently of the divisor 7 or the base 10.
You can compute the value of the number modulo 7.
That is, for each digit d and value n so far compute n = (10 * n + d) % 7.
This has the advantage of working independently of the divisor 7 or the base 10.
I solved this problem exactly the same way on one of programming contests. Here is the fragment of code you need:
int sum = 0;
while (true) {
char ch;
cin>>ch;
if (ch<'0' || ch>'9') break; // Reached the end of stdin
sum = sum*10; // The previous sum we had must be multiplied
sum += (int) ch;
sum -= (int) '0'; // Remove the code to get the value of the digit
sum %= 7;
}
if (sum==0) cout<<"1";
else cout<<"0";
This code is working thanks to simple rules of modular arithmetics. It also works not just for 7, but for any divisor actually.
I'd start by subtracting some big number which is divisible by 7.
Examples of numbers which are divisible by 7 include 700, 7000, 70000, 140000000, 42000000000, etc.
In the particular example you gave, try subtracting 280000000000(some number of zeros)0000.
Even easier to implement, repeatedly subtract the largest possible number like 70000000000(some number of zeros)0000.
Because I recently did work dealing with breaking up numbers, I will hint that to get specific numbers - which is what you will need with some of the other answers - think about integer division and using the modulus to get digits out of it.
If you had a smaller number, say 123, how would you get the 1, the 2, and the 3 out of it? Especially since you're working in base 10...
N = abc
There is a simple algorithm to verify if a three-digit number is a multiple of 7:
Substitute a by x and add it to bc, being x the tens of a two-digit number multiple of 7 whose hundreds is a.
N = 154; x = 2; 2 + 54 = 56; 7|56 and 7|154
N = 931; x = 4; 4 + 31 = 35; 7|35 and 7|931
N = 665; x = 5; 5 + 65 = 70; 7|70 and 7|665
N = 341; x = 6; 6 + 41 = 47; 7ł47 and 7ł341
If N is formed by various periods the inverse additive of the result of one period must be added to the sum of the next period, this way:
N = 341.234
6 + 41 = 47; - 41 mod 7 ≡ 1; 1 + 4 + 34 = 39; 7ł39 and 7łN
N = 341.234.612.736.481
The result for 341.234 is 39. Continuing from this result we have:
-39 mod 7 ≡ 3; 3 + 5 + 6 + 1 + 2 + 1 = 18; - 18 mod 7 ≡ 3; 3 + 0 + 36 = 39; - 39 mod 7 ≡ 3;
3 + 1 + 81 = 85; 7ł85 and 7łN
This rule may be applied entirely through mental calculation and is very quick.
It was derived from another rule that I created in 2.005. It works for numbers of any magnitude and for divisibility by 13.
At first Take That Big Number in string And then sum every digit of string. at last check if(sum%7==0)
Code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long int n,i,j,sum,k;
sum=0;
string s;
cin>>s;
for(i=0;i<s.length();i++)
{
sum=sum+(s[i]-'0');
}
if(sum%7==0)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
return 0;
}