Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
What does rand() do in C? I don't use C++, just C.
Visual Studio 2012 tells me that its return type is int __cdecl
And it is part of stdlib.h
It does not take any parameters.
How can I set the range in which it generates (pseudo)random numbers?
Your answers are greatly appreciated
Now that there's an actual question: You can't. The range is fixed, and it's defined by the constant RAND_MAX if you need to know it (it's [0 .. RAND_MAX])
If you want a different range, you have to arrange that yourself, typically using the modulo operator % and optionally an offset ... for random numbers between 5 and 9 use
int foo = rand() % 5 + 5;
I use a helper function like this in the game i recently wrote:
int
randomNum(int min, int max)
{
static int seeded = 0;
if (!seeded)
{
seeded = 1;
srand((unsigned int)time(0));
}
return (rand() % (max-min+1)) + min;
}
Depends on the compiler. This wiki article contains a list of them: linear congruential generator
If you need to extend the range of rand(), call it multiple times and merge the outputs:
unsigned int r;
/* ... */
r = ((rand()>>4) & 0xff)<< 0;
r += ((rand()>>4) & 0xff)<< 8;
r += ((rand()>>4) & 0xff)<<16;
r += ((rand()>>4) & 0xff)<<24;
Example program to show how rand works by comparing the returned value. This works with Microsoft compiles (no mismatch).
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char* argv[])
{
unsigned int seed = 1;
unsigned int rand1, rand2;
unsigned int i;
for(i = 0; i < 20; i++){
seed = seed*214013 + 2531011;
rand1 = (seed >> 16) & 0x7fffu;
rand2 = rand();
if(rand1 != rand2)
printf("mismatch %d %d\n", rand1, rand2);
}
return(0);
}
Since only 15 bits of the seed are returned by this version of rand(), then RAND_MAX would be 32767 or hex 0x7fff. As noted in the wiki article, the period is 2^32, this means that seed will cycle through all 4,294,967,296 possible 32 bit values, never repeating until the 4,294,967,296 call to rand(), where seed will have cycled back to 1.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 months ago.
Improve this question
when I give input as num=1, output should be 8
when I give input as num=2, output should be 16
when I give input as num=3, output should be 32
when I give input as num=4, output should be 64
and so on
Here is the code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num,b;
scanf("%d",&num);
num=num+2;
b=pow(2,num);
printf("%d",b);
return 0;
}
I tried writing my own pow() function, but interviewer did not accept the solution.
You can use bit shifting.
Firstly, let's idenitfy the pattern (which you already have, it seems): for any given num, we should print out 2 to the power of num+2.
Consider that we are working in base 2. (Most) Computers nowadays store numbers in binary. Consider the binary representation of 1, 2, 4, 8 and 16.
1 = 0b00001
2 = 0b00010
4 = 0b00100
8 = 0b01000
16 = 0b10000
Notice that for each power of 2, there is only one bit set to 1. For increasing powers of 2, this bit moves to the left. With C, we can achieve getting something like this with the left shift operator in O(1), computationally faster than the O(log num) or O(num) implementations of pow as a library function and your own implementation of pow.
Instead of b=pow(2, num), you can try b=1<<num instead. This way, when num = 3 for example, the bit will be shifted three times to get 0b01000 = 8.
A straightforward approach can look for example the following way using the bitwise left shift operator.
Pay attention to that you should define the result when the value of num (that should be of unsigned integer type) is equal to 0.
#include <stdio.h>
unsigned long long f( unsigned int n )
{
return n == 0 ? 1 : 8llu << ( n - 1 );
}
int main( void )
{
const unsigned int N = 5;
for ( unsigned int i = 0; i < N; i++ )
{
printf( "%llu ", f( i ) );
}
putchar( '\n' );
}
The program output is
1 8 16 32 64
If the goal is to optimize the pow() call, you can't really replaces this with shift operations on an integer type; then there will be lost of precision for high values of n.
However, it is quite easy to write a pow2() function for integer input; It just need to set the exponent value of a double variable (assuming it’s in IEEE 754 format). Example code:
#include <stdio.h>
double pow2i(int n)
{
short s[4] = { 0 }; // IEEE 754
s[3] = (short)((n + 0x3FF) << 4 ); // writing the exponent value
return *(double*)&s;
}
double f(int n)
{
return pow2i(n+2);
}
int main()
{
for( int i = 1; i < 201; i++ )
printf("f(%d): %.0f\n",i,f(i));
return 0;
}
This question already has answers here:
How to concatenate two integers in C
(10 answers)
Closed 5 years ago.
Currently I am having a speed bump with adding two different integers. For example
int i = 32;
int j = 50;
/* Add i and j together into 3250 */
What I thought was changing the integers into strings and add them together but that takes too much effort. Is there any other way?
The solution in the decimal system is:
int result = 100* i + j;
In case this should be generic you'll need the following algorithm:
int shift = 10;
while(j >= shift) {
pow *= 10;
}
int result = i * pow + j;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am using this code to create; but all the results are in range of 10 to 32000.
Can you tell me what I am doing wrong?
for (i = 0; i < N; i++) {
*(A + i) = rand() % (1000000000 - 10 + 1) + 10;
printf("%lu\n", *(A + i));
}
rand() returns a value in the range of 0 and RAND_MAX (which, according to the standard, is at least 32767): https://www.tutorialspoint.com/c_standard_library/c_function_rand.htm
If you want a higher value you can multiply multiple rand() results.
1,000,000,000 (3B9ACA00) is a 30-bit number.
rand() generates results in the [0...RAND_MAX] range. RAND_MAX may be as small as 32,767, a 15-bit number// RAND_MAX may be as large as INT_MAX. Multiple calls to rand() are needed when RAND_MAX < (1000000000 - 10 + 1), the number of different values sought by OP.
The below throws out small or larges values (about 7% of the time) and tries again. This is done to maintain a fair distribution of numbers.
uint32_t rand_10_to_1000000000(void) {
// This method only works well when RAND_MAX is 2**n -1.
// This is commonly true
assert((RAND_MAX + (uint32_t) 1) & RAND_MAX == 0);
uint32_t r;
do {
r = rand();
#if RAND_MAX < 0x3FFFFFFF
// Adding 1 to RAND_MAX as an int should be avoided to prevent int overflow.
r *= RAND_MAX + (uint32_t) 1;
r += rand();
#endif
r &= 0x3FFFFFFF; // only use lower 30 bits.
} while (r < 10 || r > 1000000000);
return r;
}
Here is what documentation says about rand() return value:
An integer value between 0 and RAND_MAX.
And here is what documentation says about RAND_MAX:
This value is library-dependent, but is guaranteed to be at least 32767 on any standard library implementation.
So in your implementation RAND_MAX can probably generate numbers up to 32767. You probably have to generate upper and lower bits independently like:
int big_rand()
{
return rand() | (rand() << 15);
}
Your system's implementation of rand() has limited precision. The standard mandates that RAND_MAX be at least 32767. You system seems to use this minimum value.
You can combine multiple random values to compute your samples:
for (i = 0; i < N; i++) {
A[i] = 10 + (rand() | ((unsigned)rand() << 15)) % (1000000000 - 10 + 1);
printf("%lu\n", A[i]);
}
PS: why do you write *(A+i) instead of the more readable A[i]?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I have some code here that I have been studying. It converts decimal numbers to binary. The code runs smoothly but what's bugging me are the variables. The code is as follows:
#include <stdio.h>
int main()
{
long int decimalNumber, remainder, quotient;
int binaryNumber[100], i=1, j;
printf("Enter any decimal number: ");
scanf("%ld",&decimalNumber);
quotient = decimalNumber;
while (quotient!=0) {
binaryNumber[i++]= quotient % 2;
quotient = quotient / 2;
}
printf("Equivalent binary value of decimal number %d: ", decimalNumber);
for (j = i -1 ; j> 0; j--)
printf("%d",binaryNumber[j]);
return 0;
}
I really find the variables confusing. Can someone tell me what is actually happening with the variables? Especially the one with binaryNumber[100],binaryNumber[i++], binaryNumber[j], and the expression binaryNumber[i++] = quotient % 2
binaryNumber is an array of ints, i.e. of integers. It is of size 100. It goes from 0...99 (binaryNumber[0] is the first element and binaryNumber[99] is the last). The array can contain 100 integers, of different or equal values. They don't actually have to be of value 0...99 but anything else that is in the range of int (read comment).
When you perform int binaryNumber[100] you define this array.
When you perform binaryNumber[i++] you access the element in the location i of this array, and then increment i. Meaning you perform i = i + 1;.
Same goes for binaryNumber[j].
When you perform binaryNumber[i++] = quotient % 2 you assign the value of quotient % 2 to the binaryNumber array at position i like stated before (and increment i).
If you're wondering about the modulus operator (%) read here.
binaryNumber[100]: This is actually an array of 100 integers. The first integer in the array could be accessed by binaryNumber[0] etc.
binaryNumber[j]: This means the (j-1)th integer in the array.
binaryNumber[i++]: Lets say i=3 when this statement runs. binaryNumber[i++] is equivalent to binaryNumber[3], which is the 4th integer. However, after this statement is executed, i is incremented to 4.
quotient % 2:
% is actually the modulus operator. Example: 13 % 4 = remainder of 13/4 = 1.
binaryNumber[100] : it is an array , a sepuence of elements of type "long int" you can access a spesific element using "array[index] = value" .
binaryNumber[i++] : access the element nember i then increament i , example if i=1 then you acces binaryNumber[1] then i become 2 (after usage ).
binaryNumber[j] : access the element nember j , j is a variable and can be used as a index , then you will acces the element nember the current value of j .
binaryNumber[i++] = quotient % 2 : it tell the compiler to let the element nember i in the binaryNumber take the value of quotient % 2 that is the math modulos , like 9%2=1 ; 5%3=2 , the rest of the quotient pear 2
comment for more informations .
A simple way to do the conversion is a loop and shift. You can put it in a function to make the conversion look nice. Here is an example:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h> /* for CHAR_BIT */
void binprn (const unsigned long v);
int main (int argc, char **argv) {
long unsigned a = argc > 1 ? strtoul (argv[1], NULL, 10) : 4327;
printf ("\n %lu decimal, binary: ", a);
binprn (a);
putchar ('\n');
return 0;
}
/** unpadded binary representation of 'v'. */
void binprn (const unsigned long v)
{
if (!v) { putchar ('0'); return; };
size_t sz = sizeof v * CHAR_BIT;
unsigned long rem = 0;
while (sz--)
if ((rem = v >> sz))
putchar ((rem & 1) ? '1' : '0');
}
Use/Output
$ ./bin/dec2bin
4327 decimal, binary: 1000011100111
$ ./bin/dec2bin 10
10 decimal, binary: 1010
$ ./bin/dec2bin 127
127 decimal, binary: 1111111
This question already has answers here:
Why does rand() always return the same value? [duplicate]
(2 answers)
Closed 7 years ago.
I have a big problem , I do not understand.
I need to generate random numbers from the interval.
I am using code:
unsigned int nahodnyCisloZIntervalu(unsigned int min, unsigned int max) {
int r;
const unsigned int range = 1 + max - min;
const unsigned int buckets = RAND_MAX / range;
const unsigned int limit = buckets * range;
do {
r = rand();
} while (r >= limit);
return min + (r / buckets);
}
But every time you start the program generates the same numbers!
How to generate truly random numbers usnig C?
Use the standard rand function. It is normal that rand returns the same sequence each time.
Use the srand function at the beginning of your program in order to initialize the random number generator with a "seed", using for example the current time as seed.