Hi
It is possible to generate random number within a range (-x,x) using rand()?? If not, how can I generate random number withing that range ?
// return a random number between 0 and limit inclusive.
int rand_lim(int limit) {
int divisor = RAND_MAX/(limit+1);
int retval;
do {
retval = rand() / divisor;
} while (retval > limit);
return retval;
}
// Return a random number between lower and upper inclusive.
int rand_lim(int lower, int upper) {
int range = abs(upper-lower);
return rand_lim(range) + lower;
}
As usual, all the others I've seen in this thread can/will produce at least slightly skewed results.
I am just a simple Basic programmer, but I feel like I am missing the point. The answer seems simple. Please pardon the VB code
Dim prng As New Random
Const numEach As Integer = 100000
Const x As Integer = 3 'generate random number within a range (-x,x) inclusive
Dim lngth As Integer = Math.Abs(-x - x) + 1
Dim foo(lngth - 1) As Integer 'accumualte hits here
For z As Integer = 1 To (numEach * lngth)
Dim n As Integer = prng.Next(lngth) 'generate number in inclusive range
foo(n) += 1 'count it
'n = x - n 'actual n
Next
Debug.WriteLine("Results")
For z As Integer = 0 To foo.Length - 1
Debug.WriteLine((z - x).ToString & " " & foo(z).ToString & " " & (foo(z) / numEach).ToString("n3"))
Next
Debug.WriteLine("")
Typical results
Results
-3 99481 0.995
-2 100214 1.002
-1 100013 1.000
0 100361 1.004
1 99949 0.999
2 99755 0.998
3 100227 1.002
Results
-3 100153 1.002
-2 99917 0.999
-1 99487 0.995
0 100383 1.004
1 100177 1.002
2 99808 0.998
3 100075 1.001
Check out the answers to this question.
Related
Why is X % 0 an invalid expression?
I always thought X % 0 should equal X. Since you can't divide by zero, shouldn't the answer naturally be the remainder, X (everything left over)?
The C++ Standard(2003) says in §5.6/4,
[...] If the second operand of / or % is zero the behavior is undefined; [...]
That is, following expressions invoke undefined-behavior(UB):
X / 0; //UB
X % 0; //UB
Note also that -5 % 2 is NOT equal to -(5 % 2) (as Petar seems to suggest in his comment to his answer). It's implementation-defined. The spec says (§5.6/4),
[...] If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
This answer is not for the mathematician. This answer attempts to give motivation (at the cost of mathematical precision).
Mathematicians: See here.
Programmers: Remember that division by 0 is undefined. Therefore, mod, which relies on division, is also undefined.
This represents division for positive X and D; it's made up of the integral part and fractional part:
(X / D) = integer + fraction
= floor(X / D) + (X % D) / D
Rearranging, you get:
(X % D) = D * (X / D) - D * floor(X / D)
Substituting 0 for D:
(X % 0) = 0 * (X / 0) - 0 * floor(X / 0)
Since division by 0 is undefined:
(X % 0) = 0 * undefined - 0 * floor(undefined)
= undefined - undefined
= undefined
X % D is by definition a number 0 <= R < D, such that there exists Q so that
X = D*Q + R
So if D = 0, no such number can exists (because 0 <= R < 0)
I think because to get the remainder of X % 0 you need to first calculate X / 0 which yields infinity, and trying to calculate the remainder of infinity is not really possible.
However, the best solution in line with your thinking would be to do something like this
REMAIN = Y ? X % Y : X
Another way that might be conceptually easy to understand the issue:
Ignoring for the moment the issue of argument sign, a % b could easily be re-written as a - ((a / b) * b). The expression a / b is undefined if b is zero, so in that case the overall expression must be too.
In the end, modulus is effectively a divisive operation, so if a / b is undefined, it's not unreasonable to expect a % b to be as well.
X % Y gives a result in the integer [ 0, Y ) range. X % 0 would have to give a result greater or equal to zero, and less than zero.
you can evade the "divivion by 0" case of (A%B) for its type float identity mod(a,b) for float(B)=b=0.0 , that is undefined, or defined differently between any 2 implementations, to avoid logic errors (hard crashes) in favor of arithmetic errors...
by computing mod([a*b],[b])==b*(a-floor(a))
INSTREAD OF
computing mod([a],[b])
where [a*b]==your x-axis, over time
[b] == the maximum of the seesaw curve (that will never be reached) == the first derivative of the seesaw function
https://www.shadertoy.com/view/MslfW8
I suppose because to get the remainder of X % 0 you need to first calculate X / 0 which yields infinity, and trying to calculate the remainder of infinity is not really possible.
However, the best solution in line with your thinking would be to do something like this,
ans = Y ? X % Y : X
Also, in C++ docs its written that X % 0 or X / 0 ,results in an undefined value.
How computers divide:
Start with the dividend and subtract the divisor until the result is less then the divisor. The number of times you subtracted is the result and what you have left is the remainder. For example, to divide 10 and 3:
10 - 3 = 7
7 - 3 = 4
4 - 3 = 1
So
10 / 3 = 3
10 % 3 = 1
To divide 1 and 0:
1 / 0
1 - 0 = 1
1 - 0 = 1
1 - 0 = 1
...
So
1 / 0 = Infinity (technically even infinity is too small, but it's easy to classify it as that)
1 % 0 = NaN
If there is nothing to stop it, the CPU will continue to execute this until it overloads and returns a totally random result. So there is an instruction at the CPU level that if the divisor is 0, return NaN or Infinity (depending on your platform).
This will never end so the remainder is undefined (which is NaN for computers).
I'm being requested to write a C++ program that computes the n-th number that doesn't contain a given digit and the time execution to be lower than 0.1 seconds. Memory doesn't seem to be an issue, as I'm allowed the use of up to 64 MB.
The original text of the problem goes like this:
Cifra4
To represent numbers, it was decided not to use the digit C
again.
Thus, from the array of natural numbers, all numbers containing the
digit C will be erased. Let the new array be S.
Requirements
1) Determine the N-th number in S.
2) Y and Z are two natural
numbers from the array of all natural numbers. Determine the number of
natural numbers removed from Y to Z.
Input data
The input file cifra4.in contains the first number T representing the
type of requirement. If T == 1, the second row will contain
the digit C and the number N. If T == 2, the
second line will contain the digit C and two natural numbers Yand
Z.
Output data
In the output file cifra4.out will contain in the first row
one natural number according to the type of requirement.
Restrictions and clarifications
1 ≤ N ≤ 10 ^ 13
0 ≤ C ≤ 9
1 ≤ Y ≤ 10 ^ 13
1 ≤ Z ≤ 10 ^ 13
for 20% of the tests, N will have a maximum of 5 digits
for 20% of the tests, Y and Z will have a maximum of 6 digits
Example 1
cifra4.in
1
0 11
cifra4.out
12
Example 2
cifra4.in
2
1 3 20
cifra4.out
10
My best try was a code that determined (or at least was supposed to) the n-th number that doesn't contain the digit "0", but for 10 ^ 13 it returned 23210987654321, which obviously contains 0.
My slower, but correct approach was what I ended up keeping. Here is the code:
#include <fstream>
std::ifstream in("cifra4.in");
std::ofstream out("cifra4.out");
const long long pow_of_10[14] = {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000,
10000000000, 100000000000, 1000000000000};
void req_1 ()
{
short digit;
long long n;
in >> digit >> n;
for (long long i = 0; i <= n; i++)
{
long long nr = i;
if (nr)
{
long k = 1;
do
{
if (nr % 10 == digit)
{
n += pow_of_10[k];
i += pow_of_10[k] - 1;
break;
}
nr /= 10;
k++;
}
while (nr);
}
else if (digit == 0) n++;
}
out << n - 1;
}
void req_2()
{
short digit;
long long lhs, rhs;
long long elim = 0;
in >> digit >> lhs >> rhs;
for (long long i = lhs; i <= rhs; i++)
{
long long nr = i;
while (nr)
{
if (nr % 10 == digit)
{
elim++;
break;
}
nr /= 10;
}
}
out << elim;
}
int main()
{
short requirement;
in >> requirement;
if (requirement == 1)
req_1();
else
req_2();
}
NOTE
I'm not asking for code necesarily, but for ideas, possible algorithms that can execute up to 10 ^ 13 in decent time, preferably the time requested by the problem, but 1 second will do fine for me.
Imagine that 9 is the forbidden digit. In this case you can just convert your number to base-9 and you're done.
Now, what happens when the forbidden digit is different, say d? It's still a base-9 number but you have to map your digits, such that digits below d remain unaffected, and d and above are mapped to the digit d + 1.
For example, when the forbidden digit is 7 and n is 125.
Step 1: convert to base-9: 12510 = 1489
Step 2: map the digits. 1 → 1, 4 → 4, 8 → 9
The solution is 149.
Since the decimal digits of a number are "independent" of each other, in that setting one digit does not affect any other digits - once you've fixed a prefix of (at least one) more-significant digits, leaving n' less-significant digits, you know you have exactly (10 - 1)^n' = 9^n' numbers with that prefix and no forbidden digits in the unfixed part. For example, for 3-digit numbers beginning with 1, there are exactaly 81 numbers with no 0 in them.
The only 'snag' here is that setting the most-significant digit to zero means that you get the same number for different numbers of digits (012, 0012 etc.). But you should be able to work around this issue as well - by determining how many digits you're going to need for the n'th number without your forbidden digit. Very similar to the argument I described above. Then you know you have 10-1 = 9 options there if your forbidden digit is 0 or 10-2 = 8 otherwise.
So the following code makes 0 < r < 1
r = ((double) rand() / (RAND_MAX))
Why does having r = ((double) rand() / (RAND_MAX + 1)) make -1 < r < 0?
Shouldn't adding one to RAND_MAX make 1 < r < 2?
Edit: I was getting a warning: integer overflow in expression
on that line, so that might be the problem. I just did cout << r << endl and it definitely gives me values between -1 and 0
This is entirely implementation specific, but it appears that in the C++ environment you're working in, RAND_MAX is equal to INT_MAX.
Because of this, RAND_MAX + 1 exhibits undefined (overflow) behavior, and becomes INT_MIN. While your initial statement was dividing (random # between 0 and INT_MAX)/(INT_MAX) and generating a value 0 <= r < 1, now it's dividing (random # between 0 and INT_MAX)/(INT_MIN), generating a value -1 < r <= 0
In order to generate a random number 1 <= r < 2, you would want
r = ((double) rand() / (RAND_MAX)) + 1
rand() / double(RAND_MAX) generates a floating-point random number between 0 (inclusive) and 1 (inclusive), but it's not a good way for the following reasons (because RAND_MAX is usually 32767):
The number of different random numbers that can be generated is too small: 32768. If you need more different random numbers, you need a different way (a code example is given below)
The generated numbers are too coarse-grained: you can get 1/32768, 2/32768, 3/32768, but never anything in between.
Limited states of random number generator engine: after generating RAND_MAX random numbers, implementations usually start to repeat the same sequence of random numbers.
Due to the above limitations of rand(), a better choice for generation of random numbers between 0 (inclusive) and 1 (exclusive) would be the following snippet (similar to the example at http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution ):
#include <iostream>
#include <random>
#include <chrono>
int main()
{
std::mt19937_64 rng;
// initialize the random number generator with time-dependent seed
uint64_t timeSeed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
std::seed_seq ss{uint32_t(timeSeed & 0xffffffff), uint32_t(timeSeed>>32)};
rng.seed(ss);
// initialize a uniform distribution between 0 and 1
std::uniform_real_distribution<double> unif(0, 1);
// ready to generate random numbers
const int nSimulations = 10;
for (int i = 0; i < nSimulations; i++)
{
double currentRandomNumber = unif(rng);
std::cout << currentRandomNumber << std::endl;
}
return 0;
}
This is easy to modify to generate random numbers between 1 (inclusive) and 2 (exclusive) by replacing unif(0, 1) with unif(1, 2).
No, because RAND_MAX is typically expanded to MAX_INT. So adding one (apparently) puts it at MIN_INT (although it should be undefined behavior as I'm told), hence the reversal of sign.
To get what you want you will need to move the +1 outside the computation:
r = ((double) rand() / (RAND_MAX)) + 1;
It doesn't. It makes 0 <= r < 1, but your original is 0 <= r <= 1.
Note that this can lead to undefined behavior if RAND_MAX + 1 overflows.
This is the right way:
double randd() {
return (double)rand() / ((double)RAND_MAX + 1);
}
or
double randd() {
return (double)rand() / (RAND_MAX + 1.0);
}
My guess is that RAND_MAX is equal to INT_MAX and so you're overflowing it to a negative.
Just do this:
r = ((double) rand() / (RAND_MAX)) + 1;
Or even better, use C++11's random number generators.
this->value = rand() % (this->max + 1);
Seems to work fine between 0 and 1++.
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;
}