How do I find the next multiple of 10 of any integer? - c

Dynamic integer will be any number from 0 to 150.
i.e. - number returns 41, need to return 50. If number is 10 need to return 10. Number is 1 need to return 10.
Was thinking I could use the ceiling function if I modify the integer as a decimal...? then use ceiling function, and put back to decimal?
Only thing is would also have to know if the number is 1, 2 or 3 digits (i.e. - 7 vs 94 vs 136)
Is there a better way to achieve this?
Thank You,

n + (10 - n % 10)
How this works. The % operator evaluates to the remainder of the division (so 41 % 10 evaluates to 1, while 45 % 10 evaluates to 5). Subtracting that from 10 evaluates to how much how much you need to reach the next multiple.
The only issue is that this will turn 40 into 50. If you don't want that, you would need to add a check to make sure it's not already a multiple of 10.
if (n % 10)
n = n + (10 - n % 10);

You can do this by performing integer division by 10 rounding up, and then multiplying the result by 10.
To divide A by B rounding up, add B - 1 to A and then divide it by B using "ordinary" integer division
Q = (A + B - 1) / B
So, for your specific problem the while thing together will look as follows
A = (A + 9) / 10 * 10
This will "snap" A to the next greater multiple of 10.
The need for the division and for the alignment comes up so often that normally in my programs I'd have macros for dividing [unsigned] integers with rounding up
#define UDIV_UP(a, b) (((a) + (b) - 1) / (b))
and for aligning an integer to the next boundary
#define ALIGN_UP(a, b) (UDIV_UP(a, b) * (b))
which would make the above look as
A = ALIGN_UP(A, 10);
P.S. I don't know whether you need this extended to negative numbers. If you do, care should be taken to do it properly, depending on what you need as the result.

What about ((n + 9) / 10) * 10 ?
Yields 0 => 0, 1 => 10, 8 => 10, 29 => 30, 30 => 30, 31 => 40

tl;dr: ((n + 9) / 10) * 10 compiles to the nicest (fastest) asm code in more cases, and is easy to read and understand for people that know what integer division does in C. It's a fairly common idiom.
I haven't investigated what the best option is for something that needs to work with negative n, since you might want to round away from zero, instead of still towards +Infinity, depending on the application.
Looking at the C operations used by the different suggestions, the most light-weight is Mark Dickinson's (in comments):
(n+9) - ((n+9)%10)
It looks more efficient than the straightforward divide / multiply suggested by a couple people (including #bta): ((n + 9) / 10) * 10, because it just has an add instead of a multiply. (n+9 is a common subexpression that only has to be computed once.)
It turns out that both compile to literally identical code, using the compiler trick of converting division by a constant into a multiply and shift, see this Q&A for how it works. Unlike a hardware div instruction that costs the same whether you use the quotient, remainder, or both results, the mul/shift method takes extra steps to get the remainder. So the compiler see that it can get the same result from a cheaper calculation, and ends up compiling both functions to the same code.
This is true on x86, ppc, and ARM, and all the other architectures I've looked at on the Godbolt compiler explorer. In the first version of this answer, I saw an sdiv for the %10 on Godbolt's gcc4.8 for ARM64, but it's no longer installed (perhaps because it was misconfigured?) ARM64 gcc5.4 doesn't do that.
Godbolt has MSVC (CL) installed now, and some of these functions compile differently, but I haven't taken the time to see which compile better.
Note that in the gcc output for x86, multiply by 10 is done cheaply with lea eax, [rdx + rdx*4] to do n*5, then add eax,eax to double that. imul eax, edx, 10 would have 1 cycle higher latency on Intel Haswell, but be shorter (one less uop). gcc / clang don't use it even with -Os -mtune=haswell :/
The accepted answer (n + 10 - n % 10) is even cheaper to compute: n+10 can happen in parallel with n%10, so the dependency chain is one step shorter. It compiles to one fewer instruction.
However, it gives the wrong answer for multiples of 10: e.g. 10 -> 20. The suggested fix uses an if(n%10) to decide whether to do anything. This compiles into a cmov, so it's longer and worse than #Bta's code. If you're going to use a conditional, do it to get sane results for negative inputs.
Here's how all the suggested answers behave, including for negative inputs:
./a.out | awk -v fmt='\t%4s' '{ for(i=1;i<=NF;i++){ a[i]=a[i] sprintf(fmt, $i); } } END { for (i in a) print a[i]; }'
i -22 -21 -20 -19 -18 -12 -11 -10 -9 -8 -2 -1 0 1 2 8 9 10 11 12 18 19 20 21 22
mark -10 -10 -10 -10 0 0 0 0 0 0 0 0 0 10 10 10 10 10 20 20 20 20 20 30 30
igna -10 -10 -10 0 0 0 0 0 10 10 10 10 10 10 10 10 10 20 20 20 20 20 30 30 30
utaal -20 -20 -20 -10 -10 -10 -10 -10 0 0 0 0 0 10 10 10 10 10 20 20 20 20 20 30 30
bta -10 -10 -10 -10 0 0 0 0 0 10 10 10 10 10 10 10 10 10 20 20 20 20 20 30 30
klatchko -10 -10 -10 -10 0 0 0 0 0 0 0 0 0 10 10 10 10 10 20 20 20 20 20 30 30
branch -10 -10 -20 0 0 0 0 -10 10 10 10 10 0 10 10 10 10 10 20 20 20 20 20 30 30
(transpose awk program)
Ignacio's n + (((9 - (n % 10)) + 1) % 10) works "correctly" for negative integers, rounding towards +Infinity, but is much more expensive to compute. It requires two modulo operations, so it's essentially twice as expensive. It compiles to about twice as many x86 instructions, doing about twice the work of the other expressions.
Result-printing program (same as the godbolt links above)
#include <stdio.h>
#include <stdlib.h>
int f_mark(int n) { return (n+9) - ((n+9)%10); } // good
int f_bta(int n) { return ((n + 9) / 10) * 10; } // compiles to literally identical code
int f_klatchko(int n) { return n + 10 - n % 10; } // wrong, needs a branch to avoid changing multiples of 10
int f_ignacio(int n) { return n + (((9 - (n % 10)) + 1) % 10); } // slow, but works for negative
int roundup10_utaal(int n) { return ((n - 1) / 10 + 1) * 10; }
int f_branch(int n) { if (n % 10) n += (10 - n % 10); return n; } // gcc uses cmov after f_accepted code
int main(int argc, char**argv)
{
puts("i\tmark\tigna\tutaal\tbta\tklatch\tbranch");
for (int i=-25 ; i<25 ; i++)
if (abs(i%10) <= 2 || 10 - abs(i%10) <= 2) // only sample near interesting points
printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\n", i, f_mark(i), f_accepted(i),
f_ignacio(i), roundup10_utaal(i), f_bta(i), f_branch(i));
}

How about using integer math:
N=41
N+=9 // Add 9 first to ensure rounding.
N/=10 // Drops the ones place
N*=10 // Puts the ones place back with a zero

in C, one-liner:
int inline roundup10(int n) {
return ((n - 1) / 10 + 1) * 10;
}

Be aware that answers based on the div and mod operators ("/" and "%") will not work for negative numbers without an if-test, because C and C++ implement those operators incorrectly for negative numbers. (-3 mod 5) is 2, but C and C++ calculate (-3 % 5) as -3.
You can define your own div and mod functions. For example,
int mod(int x, int y) {
// Assert y > 0
int ret = x % y;
if(ret < 0) {
ret += y;
}
return ret;
}

n + (((9 - (n % 10)) + 1) % 10)

You could do the number mod 10. Then take that result subtract it from ten. Then add that result to the original.
if N%10 != 0 #added to account for multiples of ten
a=N%10
N+=10-a

int n,res;
...
res = n%10 ? n+10-(n%10) : n;
or
res = (n / 10)*10 + ((n % 10) ? 10:0);

In pseudo code:
number = number / 10
number = ceil(number)
number = number * 10
In Python:
import math
def my_func(x):
return math.ceil(x / 10) * 10
That should do it. Keep in mind that the above code will cast an integer to a float/double for the arithmetic, and it can be changed back to an integer for the final return. Here's an example with explicit typecasting
In Python (with typecasting):
import math
def my_func(x):
return int(math.ceil(float(x) / 10) * 10)

round_up(int i)
{
while(i%10) {
i++;
}
return(i);
}

Related

C Programming what happens exactly with this recursive function

i have this function that when i start it prints only even numbers of the entered parameter can anyone explain to me what exactly happens in this function and how it ends up getting the even numbers
#include <stdio.h>
int what(int x){
if (x == 0)
return 0;
if (x % 2 == 0)
return what(x / 10) * 10 + x % 10;
return what(x / 10);
}
int main(){
printf("%d\n",what(145825));
return 0;
}
output
482
Here's what happens:
The what() function starts with the rightmost digit (= the whole number modulo 10) and then recurses into the rest of the digits by throwing away the rightmost digit (integer division by 10 throws away the right decimal digit).
If the right digit is even it is appended to the result of the recursion by multiplying it by 10 (making space for the extra digit on the right) and adding this digit (= the whole number modulo 10).
If the right digit is odd nothing is added to the result of the recursion.
Recursion stops when there are no more digits.
A good way to figure out to make recursion is to make a table that keeps track of what happens during each step, but of course a debugger is always the best way to really check what happens.
The following table is what happens each time what() is called:
x recursive x result even? returns
------ ----------- ------ ------- -------
145825 14582 482 - 482
______/ \_____________
/ \
14582 1458 48 48*10+2= 482
1458 145 4 4*10+8= 48
145 14 4 - 4
14 1 0 0*10+4= 4
1 0 0 - 0
0 - - - 0

Should I use "rand % N" or "rand() / (RAND_MAX / N + 1)"?

I was reading the C FAQ and found out in a question that it recommends me to use rand() / (RAND_MAX / N + 1) instead of the more popular way which is rand() % N.
The reasoning for that is that when N is a low number rand() % N will only use a few bits from rand().
I tested the different approaches with N being 2 on both Windows and Linux but could not notice a difference.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 2
int main(void)
{
srand(0);
printf("rand() %% N:\n");
for (int i = 0; i < 40; ++i) {
printf("%d ", rand() % N);
}
putchar('\n');
srand(0);
printf("rand() / (RAND_MAX / N + 1):\n");
for (int i = 0; i < 40; ++i) {
printf("%d ", rand() / (RAND_MAX / N + 1));
}
putchar('\n');
return 0;
}
The output is this (on my gnu/linux machine):
rand() % N:
1 0 1 1 1 1 0 0 1 1 0 1 0 1 1 0 0 0 0 0 1 0 1 1 0 0 0 1 1 1 1 0 0 0 1 1 1 0 1 0
rand() / (RAND_MAX / N + 1):
1 0 1 1 1 0 0 1 0 1 0 1 0 1 1 1 1 1 0 1 0 0 0 1 0 0 0 0 1 0 1 1 1 0 1 1 0 1 0 1
Both alternatives seem perfectly random to me. It even seems like the second approach is worse than rand % N.
Should I use rand() % N or rand() / (RAND_MAX / N + 1)?
If N is a power of two, using the remainder technique is usually safe (RAND_MAX is usually a power of two minus 1, so the entire range has a power of two length). More generally, N has to divide the range of rand() in order to avoid the bias.
Otherwise, you run into this problem, regardless of the quality of rand(). In short, the problem is that you're chopping that range into a number of "parts" each of length N, if N does not divide the range then the last part will not be complete. The numbers that got "cut off" from that part are therefore less likely to occur, since they have one fewer "part" they can be generated from.
Unfortunately rand() / (RAND_MAX / N + 1) is also broken (in almost the same way), so the real answer is: don't use either of them.
The problem as outlined above is really fundamental, there is no way to evenly distribute X different values over Y results unless Y divides X. You can fix it by rejecting a part of the random samples, to make Y divide the new X.
There is another problem with rand() % n which is that it introduces a modulo bias.
For simplicity's sake let's pretend RAND_MAX is 7 and n is 6. You want the numbers 0, 1, 2, 3, 4, 5 to appear in the random stream with equal probability. However, 0 and 1 will appear 1/4 of the time and the other numbers only 1/8th of the time because 6 and 7 have remainders 0 and 1 respectively. You should use the other method, but carefully because truncation of fractions might introduce a similar issue.
If you have arc4random(), you can use arc4random_uniform() to achieve an unbiased distribution without having to be careful.
On avr-gcc:
I was using rand() & 0xFF to get random number from 0 to 255 and the results were not good. Turned out, that using lower bits is not very reliable method, often the same values. Could be similar with modulo.
rand() / (RAND_MAX / N + 1) worked much better for me

Minimum base of a number which makes it a palindrome when represented in that base

Given an Integer x, I have to find a minimum baseb(b > 1) such that x base b is a palindrome.
Eg: 5 base 2 is a palindrome i.e. 5 in base 2 : 101 is a palindrome. How to solve it in a better way other than solving it brute-force?
Fair warning: this is not a complete answer, but some notes which may be useful. Hopefully given the unorthodox nature of the question and comments so far, no one will be too upset by this. :)
Base 2
11: 3
101: 5 (+2) d
111: 7 (+2) 2
1001: 9 (+2) d
1111: 15 (+6) 2
10001: 17 (+2) d
10101: 21 (+4)
11011: 27 (+6) 2
11111: 31 (+4)
100001: 33 (+2) d
101101: 45 (+12)
110011: 51 (+6) 2
111111: 63 (+12)
Base 3
11: 4
22: 8 (+4) 1
101: 10 (+2) d
111: 13 (+3)
121: 16 (+3)
202: 20 (+4) 1
212: 23 (+3)
222: 26 (+3)
1001: 28 (+2) d
1111: 40 (+12)
1221: 52 (+12)
2002: 56 (+4) 1
2112: 68 (+12)
2222: 80 (+12)
Base 4
11: 5
22: 10 (+5) 1
33: 15 (+5) 1
101: 17 (+2) d
111: 21 (+4)
121: 25 (+4)
131: 29 (+4)
202: 34 (+5) 1
212: 38 (+4)
222: 42 (+4)
232: 46 (+4)
303: 51 (+5) 1
313: 55 (+4)
323: 59 (+4)
333: 63 (+4)
I marked the difference from previous as (+n) and on the end added some notes:
1: the first digit incremented here
2: the second digit incremented here (I only marked this for base 2; it seemed irrelevant elsewhere)
d: the number of digits incremented here (and the first digit reset to 1)
Some structural observations:
The first (smallest) palindrome in a base is always (base+1). We don't allow 1, nor any leading zeros.
The first N palindromes for (N < base) are N*(base+1).
The (base)th palindrome is always 2 more than (base-1)th (and is always represented as 101).
The number of 2-digit palindromes is (base-1).
The number of 3- and 4-digit palindromes is (base-1)*base.
And finally, some less-developed ideas:
The number of digits of the palindrome representation of x is 1+log_base(x).
The first palindrome of a given length is always 10..01.
You can see patterns of repeating differences when there is no marker on the end (i.e. when the first digit and the count of digits are both unchanged). This may let us "fast forward" through the candidate palindromes starting from 10..01.
This has to be solved in a brute manner, but you can avoid making it a brute-force search by applying some logic to your approach, eliminating some of the candidates.
For example, you can avoid testing for bases which the number is divisible with, thus save a base conversion process as well as a palindrome test. The reason is simple: Representation in any base may not start with a zero, and this means that a number may not end with a zero in that representation as well, otherwise would not be a palindrome.
A number ending with a zero in a base x representation means that that number is divisible with x without a remainder.
This hint cannot be carried over to other digits, because rest could be anything that is representable in that base.
Unfortunately, I cannot come up with any other generalized logic to eliminate candidates. I can, however, come up with another one that will bring down the upper bound for bases to check for candidates, after which it can be surely said that the answer is simply base (x - 1) for that x.
Base (x - 1) for x produces 11 as the representation, which is a palindrome. As the bases decrease, either the digits in the representation become larger, or we get more digits.
The next-smallest palindrome in base 2 would be 101
The next-smallest palindrome in any base greater than 2 would be 22
Let's do the checking from reverse, start from top:
for (int base = x - 1; base >= 2; base--)
// is x represented palindromic at base (base)
Imagine this for a large x. The answer will be yes initially, then we will start having a no for a long while for sure. Why is that? Let me demonstrate:
/*
base representation
x - 1 11
x - 2 12
x - 3 13
x - 4 14
...
x - n 1n
...
x-x/2 20 or 21 for x even or odd
x / 2 20 or 21 for x even or odd
Until x / 2, the second digit (from last) will stay the same and the first one will increase slowly one by one.
It is similar for between x / 2 and x / 3, but the difference in between those two is way smaller (x / 6 compared to x / 2), as well as the first digit will start increasing two by two; therefore applying this logic to the rest becomes less and less significant.
Okay, for this reason, with the exception of numbers that are less than 6, if we happen to fail to find any base less than (x / 2) that yields a palindromic representation for a number x, we can safely give up and say that the answer is (x - 1).
All this text, explaining only two simple logics that can be implemented to prevent superfluous testing:
Do not check for bases that are proper divisors of the number
Short-cut to (x - 1) if checks exceed (x / 2) for numbers x greater than or equal to 6
One last discussion: If the subject is representation in different bases, why get limited by the letters in any alphabet? Especially when we're working on computers? Just use integer arrays, each element representing a digit properly with numbers and not with any letter or anything else. Just like in strings, a terminating value can be used and that could be -1. Probably a lot easier for a computer, since it won't have to convert things back and forth into letters anyway.
And here's a source code that does what I've explained above:
#include <stdio.h>
#include <malloc.h>
int ispalindrome(const int * string)
{
int length = 0;
while (string[length] != -1)
length++;
for (int i = 0; i < length / 2; i++)
{
if (string[i] != string[length - 1 - i])
return 0;
}
return 1;
}
int * converttobase(int number, int base)
{
int length = 0;
int temp = number;
while (temp)
{
length++;
temp /= base;
}
int * result = calloc(length + 1, sizeof * result);
for (int i = length - 1; i >= 0; i--)
{
result[i] = number % base;
number /= base;
}
result[length] = -1;
return result;
}
int lowestpalindromebase(int number)
{
int limit = (number < 6) ? (number + 2) : (number / 2);
// if number is more than or equal to 6, limit candidates with the half of it
// because, reasons...
for (int base = 2; base < limit; base++)
{
if (number % base) // number does have a remainder after division with base
{
int * converted = converttobase(number, base);
if (ispalindrome(converted))
{
free(converted);
return base;
}
free(converted);
}
}
return number - 1;
}
int main( )
{
for (int i = 1; i < 60; i++)
{
printf("%2d is palindromic at base %d\n", i, lowestpalindromebase(i));
}
return 0;
}
For posterity, here is a brute force approach, checking from 3 to 1000. You 'only' have to check bases from 2 to n-1, as logically n in base n-1 is always 11 -- the smallest possible base in which it's still a palindrome.
Strangely enough, only the numbers 3, 4, 6, 11, and 19 need checking all the way up to 11.
Up to 1000, there are 60 palindromes in binary, so these are found on the first try.
As can be expected, above base 36 it cannot find a palindrome for lots of numbers.
Two Three noteworthy recurring values:
any number n^2 + 1 in base n is 101.
any number n^2 in base n-1 is 121.
all results of 1[0*]1 seem to be for x^n+1.
int is_palindrome (char *string)
{
int l = strlen(string), l2 = (l+1)>>1, i = 0;
while (i < l2)
{
if (string[i] != string[l-1-i])
return 0;
i++;
}
return 1;
}
int main (void)
{
char buf[256];
int number, base, check;
int per_base[36] = { 0 };
for (number=3; number<=1000; number++)
{
check = 0;
for (base=2; base<=min(36,number-1); base++)
{
itoa (number, buf, base);
if (is_palindrome (buf))
{
check++;
per_base[base]++;
printf ("%d in base %d is %s\n", number, base, buf);
break;
}
}
if (!check)
printf ("%d is not a palindrome in anything up to 36\n", number);
}
for (number=2; number<36; number++)
printf ("%d-ary palindromes: %d\n", number, per_base[number]);
return 0;
}

Finding the Remainder after Division in C

You need to use division and remainder by 10,
Consider this example,
163 divided by 10 is 16 and remainder is 3
16 divided by 10 is 1 and remainder is 6
1 divided by 10 is 0 and remainder is 1
Notice that the remainder is always the last digit of the number that's being divided.
How can I do this in C?
It looks like homework so I won't give you code, but I suggest you research the modulo operator and how this could be used to solve your assignment.
Use the Modulus operator:
remainder = 163 % 10; // remainder is 3
It works for any number too:
remainder = 17 % 8; // remainder is 1, since 8*2=16
(This works for both C and C#)
With the modulus operator (%):
15 % 12 == 3
17 % 8 == 1

How do I get a specific range of numbers from rand()?

srand(time(null));
printf("%d", rand());
Gives a high-range random number (0-32000ish), but I only need about 0-63 or 0-127, though I'm not sure how to go about it. Any help?
rand() % (max_number + 1 - minimum_number) + minimum_number
So, for 0-65:
rand() % (65 + 1 - 0) + 0
(obviously you can leave the 0 off, but it's there for completeness).
Note that this will bias the randomness slightly, but probably not anything to be concerned about if you're not doing something particularly sensitive.
You can use this:
int random(int min, int max){
return min + rand() / (RAND_MAX / (max - min + 1) + 1);
}
From the:
comp.lang.c FAQ list · Question 13.16
Q: How can I get random integers in a certain range?
A: The obvious way,
rand() % N /* POOR */
(which tries to return numbers from 0 to N-1) is poor, because the
low-order bits of many random number generators are distressingly
non-random. (See question 13.18.) A better method is something like
(int)((double)rand() / ((double)RAND_MAX + 1) * N)
If you'd rather not use floating point, another method is
rand() / (RAND_MAX / N + 1)
If you just need to do something with probability 1/N, you could use
if(rand() < (RAND_MAX+1u) / N)
All these methods obviously require knowing RAND_MAX (which ANSI #defines in <stdlib.h>), and assume that N is much less than RAND_MAX. When N is close to RAND_MAX, and if the range of the random number
generator is not a multiple of N (i.e. if (RAND_MAX+1) % N != 0), all
of these methods break down: some outputs occur more often than
others. (Using floating point does not help; the problem is that rand
returns RAND_MAX+1 distinct values, which cannot always be evenly
divvied up into N buckets.) If this is a problem, about the only thing
you can do is to call rand multiple times, discarding certain values:
unsigned int x = (RAND_MAX + 1u) / N;
unsigned int y = x * N;
unsigned int r;
do {
r = rand();
} while(r >= y);
return r / x;
For any of these techniques, it's straightforward to shift the range,
if necessary; numbers in the range [M, N] could be generated with
something like
M + rand() / (RAND_MAX / (N - M + 1) + 1)
(Note, by the way, that RAND_MAX is a constant telling you what the
fixed range of the C library rand function is. You cannot set RAND_MAX
to some other value, and there is no way of requesting that rand
return numbers in some other range.)
If you're starting with a random number generator which returns
floating-point values between 0 and 1 (such as the last version of
PMrand alluded to in question 13.15, or drand48 in question
13.21), all you have to do to get integers from 0 to N-1 is
multiply the output of that generator by N:
(int)(drand48() * N)
Additional links
References: K&R2 Sec. 7.8.7 p. 168
PCS Sec. 11 p. 172
Quote from: http://c-faq.com/lib/randrange.html
check here
http://c-faq.com/lib/randrange.html
For any of these techniques, it's straightforward to shift the range, if necessary; numbers in the range [M, N] could be generated with something like
M + rand() / (RAND_MAX / (N - M + 1) + 1)
Taking the modulo of the result, as the other posters have asserted will give you something that's nearly random, but not perfectly so.
Consider this extreme example, suppose you wanted to simulate a coin toss, returning either 0 or 1. You might do this:
isHeads = ( rand() % 2 ) == 1;
Looks harmless enough, right? Suppose that RAND_MAX is only 3. It's much higher of course, but the point here is that there's a bias when you use a modulus that doesn't evenly divide RAND_MAX. If you want high quality random numbers, you're going to have a problem.
Consider my example. The possible outcomes are:
rand()
freq.
rand() % 2
0
1/3
0
1
1/3
1
2
1/3
0
Hence, "tails" will happen twice as often as "heads"!
Mr. Atwood discusses this matter in this Coding Horror Article
The naive way to do it is:
int myRand = rand() % 66; // for 0-65
This will likely be a very slightly non-uniform distribution (depending on your maximum value), but it's pretty close.
To explain why it's not quite uniform, consider this very simplified example:
Suppose RAND_MAX is 4 and you want a number from 0-2. The possible values you can get are shown in this table:
rand() | rand() % 3
---------+------------
0 | 0
1 | 1
2 | 2
3 | 0
See the problem? If your maximum value is not an even divisor of RAND_MAX, you'll be more likely to choose small values. However, since RAND_MAX is generally 32767, the bias is likely to be small enough to get away with for most purposes.
There are various ways to get around this problem; see here for an explanation of how Java's Random handles it.
rand() will return numbers between 0 and RAND_MAX, which is at least 32767.
If you want to get a number within a range, you can just use modulo.
int value = rand() % 66; // 0-65
For more accuracy, check out this article. It discusses why modulo is not necessarily good (bad distributions, particularly on the high end), and provides various options.
As others have noted, simply using a modulus will skew the probabilities for individual numbers so that smaller numbers are preferred.
A very ingenious and good solution to that problem is used in Java's java.util.Random class:
public int nextInt(int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while (bits - val + (n-1) < 0);
return val;
}
It took me a while to understand why it works and I leave that as an exercise for the reader but it's a pretty concise solution which will ensure that numbers have equal probabilities.
The important part in that piece of code is the condition for the while loop, which rejects numbers that fall in the range of numbers which otherwise would result in an uneven distribution.
double scale = 1.0 / ((double) RAND_MAX + 1.0);
int min, max;
...
rval = (int)(rand() * scale * (max - min + 1) + min);
Updated to not use a #define
double RAND(double min, double max)
{
return (double)rand()/(double)RAND_MAX * (max - min) + min;
}
If you don't overly care about the 'randomness' of the low-order bits, just rand() % HI_VAL.
Also:
(double)rand() / (double)RAND_MAX; // lazy way to get [0.0, 1.0)
This answer does not focus on the randomness but on the arithmetic order.
To get a number within a range, usually we can do it like this:
// the range is between [aMin, aMax]
double f = (double)rand() / RAND_MAX;
double result = aMin + f * (aMax - aMin);
However, there is a possibility that (aMax - aMin) overflows. E.g. aMax = 1, aMin = -DBL_MAX. A safer way is to write like this:
// the range is between [aMin, aMax]
double f = (double)rand() / RAND_MAX;
double result = aMin - f * aMin + f * aMax;
Based on this concept, something like this may cause a problem.
rand() % (max_number + 1 - minimum_number) + minimum_number
// 1. max_number + 1 might overflow
// 2. max_number + 1 - min_number might overflow
if you care about the quality of your random numbers don't use rand()
use some other prng like http://en.wikipedia.org/wiki/Mersenne_twister or one of the other high quality prng's out there
then just go with the modulus.
Just to add some extra detail to the existing answers.
The mod % operation will always perform a complete division and therefore yield a remainder less than the divisor.
x % y = x - (y * floor((x/y)))
An example of a random range finding function with comments:
uint32_t rand_range(uint32_t n, uint32_t m) {
// size of range, inclusive
const uint32_t length_of_range = m - n + 1;
// add n so that we don't return a number below our range
return (uint32_t)(rand() % length_of_range + n);
}
Another interesting property as per the above:
x % y = x, if x < y
const uint32_t value = rand_range(1, RAND_MAX); // results in rand() % RAND_MAX + 1
// TRUE for all x = RAND_MAX, where x is the result of rand()
assert(value == RAND_MAX);
result of rand()
2 cents (ok 4 cents):
n = rand()
x = result
l = limit
n/RAND_MAX = x/l
Refactor:
(l/1)*(n/RAND_MAX) = (x/l)*(l/1)
Gives:
x = l*n/RAND_MAX
int randn(int limit)
{
return limit*rand()/RAND_MAX;
}
int i;
for (i = 0; i < 100; i++) {
printf("%d ", randn(10));
if (!(i % 16)) printf("\n");
}
> test
0
5 1 8 5 4 3 8 8 7 1 8 7 5 3 0 0
3 1 1 9 4 1 0 0 3 5 5 6 6 1 6 4
3 0 6 7 8 5 3 8 7 9 9 5 1 4 2 8
2 7 8 9 9 6 3 2 2 8 0 3 0 6 0 0
9 2 2 5 6 8 7 4 2 7 4 4 9 7 1 5
3 7 6 5 3 1 2 4 8 5 9 7 3 1 6 4
0 6 5
Just using rand() will give you same random numbers when running program multiple times. i.e. when you run your program first time it would produce random number x,y and z. If you run the program again then it will produce same x,y and z numbers as observed by me.
The solution I found to keep it unique every time is using srand()
Here is the additional code,
#include<stdlib.h>
#include<time.h>
time_t t;
srand((unsigned) time(&t));
int rand_number = rand() % (65 + 1 - 0) + 0 //i.e Random numbers in range 0-65.
To set range you can use formula : rand() % (max_number + 1 - minimum_number) + minimum_number
Hope it helps!
You can change it by adding a % in front of the rand function in order to change to code
For example:
rand() % 50
will give you a random number in a range of 50. For you, replace 50 with 63 or 127
I think the following does it semi right. It's been awhile since I've touched C. The idea is to use division since modulus doesn't always give random results. I added 1 to RAND_MAX since there are that many possible values coming from rand including 0. And since the range is also 0 inclusive, I added 1 there too. I think the math is arranged correctly avoid integer math problems.
#define MK_DIVISOR(max) ((int)((unsigned int)RAND_MAX+1/(max+1)))
num = rand()/MK_DIVISOR(65);
Simpler alternative to #Joey's answer. If you decide to go with the % method, you need to do a reroll to get the correct distribution. However, you can skip rerolls most of the time because you only need to avoid numbers that fall in the last bucket:
int rand_less_than(int max) {
int last_bucket_min = RAND_MAX - RAND_MAX % max;
int value;
do {
value = rand();
} while (last_bucket_min <= value);
return value % max;
}
See #JarosrawPawlak's article for explanation with diagrams: Random number generator using modulo
In case of RAND_MAX < max, you need to expand the generator: Expand a random range from 1–5 to 1–7
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // this line is necessary
int main() {
srand(time(NULL)); // this line is necessary
int random_number = rand() % 65; // [0-64]
return 0;
}
Foy any range between min_num and max_num:
int random_number = rand() % (max_num + 1 - min_num) + min_num;

Resources