I want to generate (pseudo) random numbers between 0 and some integer. I don't mind if they aren't too random. I have access to the current time of the day but not the rand function. Can anyone think of a sufficiently robust way to generate these? Perhaps, discarding some bits from time of day and taking modulo my integer or something?
I am using c.
If you're after an ultra-simple pseudo-random generator, you can just use a Linear Feedback shift Register.
The wikipedia article has some code snippets for you to look at, but basically the code for a 16-bit generator will look something like this (lightly massaged from that page...)
unsigned short lfsr = 0xACE1u;
unsigned bit;
unsigned rand()
{
bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
return lfsr = (lfsr >> 1) | (bit << 15);
}
For "not too random" integers, you could start with the current UNIX time, then use the recursive formula r = ((r * 7621) + 1) % 32768;. The nth random integer between 0 (inclusive) and M (exclusive) would be r % M after the nth iteration.
This is called a linear congruential generator.
The recursion formula is what bzip2 uses to select the pivot in its quicksort implementation. I wouldn't know about other purposes, but it works pretty well for this particular one...
Look at implementing a pseudo-random generator (what's "inside" rand()) of your own, for instance the Mersenne twister is highly-regarded.
#include <chrono>
int get_rand(int lo, int hi) {
auto moment = std::chrono::steady_clock::now().time_since_epoch().count();
int num = moment % (hi - lo + 1);
return num + lo;
}
The only "robust" (not easily predictable) way of doing this is writing your own pseudo-random number generator and seeding it with the current time. Obligatory wikipedia link: http://en.wikipedia.org/wiki/Pseudorandom_number_generator
You can get the "Tiny Mersenne Twister" here: http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/TINYMT/index.html
it is pure c and simple to use. E.g. just using time:
#include "tinymt32.h"
// And if you can't link:
#include "tinymt32.c"
#include <time.h>
#include <stdio.h>
int main(int argc, const char* argv[])
{
tinymt32_t state;
uint32_t seed = time(0);
tinymt32_init(&state, seed);
for (int i=0; i<10; i++)
printf("random number %d: %u\n", i, (unsigned int)tinymt32_generate_uint32(&state));
}
The smallest and simple random generator which work with ranges is provided below with fully working example.
unsigned int MyRand(unsigned int start_range,unsigned int end_range)
{
static unsigned int rand = 0xACE1U; /* Any nonzero start state will work. */
/*check for valid range.*/
if(start_range == end_range) {
return start_range;
}
/*get the random in end-range.*/
rand += 0x3AD;
rand %= end_range;
/*get the random in start-range.*/
while(rand < start_range){
rand = rand + end_range - start_range;
}
return rand;
}
int main(void)
{
int i;
for (i = 0; i < 0xFF; i++)
{
printf("%u\t",MyRand(10,20));
}
return 0;
}
If you're not generating your numbers too fast (*1) and your upper limit is low enough (*2) and your "time of day" includes nanoseconds, just use those nanoseconds.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int nanorand(void) {
struct timespec p[1];
clock_gettime(CLOCK_MONOTONIC, p);
return p->tv_nsec % 1000;
}
int main(void) {
int r, x;
for (;;) {
r = nanorand();
do {
printf("please type %d (< 50 quits): ", r);
fflush(stdout);
if (scanf("%d", &x) != 1) exit(EXIT_FAILURE);
} while (x != r);
if (r < 50) break;
}
puts("");
return 0;
}
And a sample run ...
please type 769 (< 50 quits): 769
please type 185 (< 50 quits): 185
please type 44 (< 50 quits): 44
(*1) if you're using them interactively, one at a time
(*2) if you want numbers up to about 1000
You can write your own rand() function. Like:
Method 1: Using the Concept of static variable:
example code:
int random_number_gen(int min_range, int max_range){
static int rand_number = 199198; // any random number
rand_number = ((rand_number * rand_number) / 10 ) % 9890;
return rand_number % (max_range+1-min_range) + min_range ;
}
Method 2. Using a random/unique value, for example, the current time in microseconds.
#include<time.h>
#include <chrono>
using namespace std;
uint64_t timeSinceEpochMicrosec() {
using namespace std::chrono;
return duration_cast<microseconds>(system_clock::now().time_since_epoch()).count();
}
int random_number_gen(int min_range, int max_range){
long long int current_time = timeSinceEpochMicrosec();
int current_time_in_sec = current_time % 10000000;
int rand_number = current_time_in_sec % (max_range+1-min_range) + min_range ;
return rand_number;
}
import java.io.*;
public class random{
public static class p{
}
static long reg=0;
static long lfsr()
{
if(reg==0)
{
reg=145896027340307l;
}
long bit=(reg>>0^reg>>2^reg>>3^reg>>5)&1;
reg=reg>>1|bit<<62;
return reg;
}
static long getRand()
{
String s=String.valueOf(new p());
//System.out.println(s);
long n=0;
lfsr();
for(int i=0;i<s.length();i++)
{
n=n<<8|+s.charAt(i);
}
System.out.print(n+" "+System.currentTimeMillis()+" "+reg+" ");
n=n^System.currentTimeMillis()^reg;
return n;
}
public static void main(String args[])throws IOException
{
for(int i=0;i<400;i++)
{
System.out.println(getRand());
}
}
}
This is a random number generator where it is guaranteed that the sequence never repeats itself. I have paired time with object value (randomly put by java) with LFSR.
Advantages:
The sequence doesn't repeat itself
The sequence is new on every run
Disadvantages:
Only compatible with java. In C++, new object that is created is same on every run.
But there too time and LFSR parameters would put in enough randomness
It is slower than most PRNGs as an object needs to be created everytime a number is needed
#include<time.h>
int main(){
int num;
time_t sec;
sec=time(NULL);
printf("Enter the Range under which you want Random number:\n");
scanf("%d",&num);
if(num>0)
{
for(;;)
{
sec=sec%3600;
if(num>=sec)
{
printf("%ld\n",sec);
break;
}
sec=sec%num;
}
}
else
{
printf("Please Enter Positive Value!\n");
}
return 0;
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
unsigned int x,r,i;
// no of random no you want to generate
scanf("%d",&x);
// put the range of random no
scanf("%d",&r);
unsigned int *a=(unsigned int*)malloc(sizeof(unsigned int)*x);
for(i=0;i<x;i++)
printf("%d ",(a[i]%r)+1);
free(a);
getch();
return 0;
}
One of the simplest random number generator which not return allways the same value:
uint16_t simpleRand(void)
{
static uint16_t r = 5531; //dont realy care about start value
r+=941; //this value must be relative prime to 2^16, so we use all values
return r;
}
You can maybe get the time to set the start value if you dont want that the sequence starts always with the same value.
Related
So ive made a MAC Address generator. But the random part is very strange. It randomly generates a number that i use to choose something from an array. But each time you run the exe. It gens the same number.
Here is my code
#include <random>
#include <string>
//Mac Addr example -> 82-F5-4D-72-C1-EA
//6 two char sets
//Dont include spaces/dashes/dots
std::string chars[] = { "A","B","C","D","E","F" };
int nums[] = { 0,1,2,3,4,5,6,7,8,9 };
std::string GenMacAddr()
{
std::string final;
std::string CharSet;
int choice;
for (int i = 0; i < 6; i++) {
choice = 1 + rand() % 4;
if (choice == 1) { //Char Set only int
for (int x = 0; x < 2; x++) { //Makes action happen twice
final += std::to_string(nums[rand()%10]);
}
}
else if (choice == 2) { //Char set only str
for (int x = 0; x < 2; x++) { //Makes action happen twice
final += chars[rand() % 6];
}
}
else if (choice == 3) {
final += chars[rand() % 6];
final += std::to_string(nums[rand() % 10]);
}
else if (choice == 4) {
final += std::to_string(nums[rand() % 10]);
final += chars[rand() % 6] ;
}
}
return final;
}
rand() is a deterministic random number generator . In order to achieve actual pseudo-random results you should first seed it with something like srand(time(NULL)) .
If you look around this you will realize that this is a bad approach and you should instead give up rand() altogether , instead use <random> from C++11 . Stephan T. Lavavej has a really nice talk about it , you should see it here .
Here is also the code snippet he recommends from that talk .
#include <random>
#include <iostream>
int main() {
std::random_device random_dev; // (Non?) deterministic random number generator
std::mt19937 mers_t(random_dev()); // Seed mersenne twister with it .
std::uniform_int_distribution<int> distribution(0, 100); // Bound the output.
// Print a random integer in the range [0,100] ( included ) .
std::cout << distribution(mers_t) << '\n';
}
EDIT:
As François noted, std::random_device isn't required to be non-deterministic and it's actually implementation dependent.
One indication to tell if it is or not is by checking the value of entropy() method call but then again some implementations return just a fixed value. In that case you might consider using std::chrono to generate a seed the way Ted describes.
rand() is a pseudo random number generator. It will generate numbers according to an algorithm designed to have a long period (before it starts repeating itself) - but it needs a starting point. This is called the seed. You seed rand() with the srand() function and you should only seed it once during the program's execution. Seeding is often done with time but since time commonly returns whole seconds (since the epoch) you risk using the same seed if you start the program more than once (within a second).
You could instead use std::random_device to generate the seed if it has entropy and use a time based seed only as a fallback.
Example:
#include <cstdlib>
#include <chrono>
#include <iostream>
#include <random>
#include <string>
#include <type_traits>
unsigned seed() { // a function to generate a seed
std::random_device rd;
if(rd.entropy() > 0.) return rd(); // if random_device has entropy, use it
// fallback, use duration since the epoch
auto dse = (std::chrono::steady_clock::now() -
std::chrono::steady_clock::time_point{}).count();
return static_cast<std::make_unsigned_t<decltype(dse)>>(dse);
}
std::string GenMacAddr() {
static const char chars[] = {'0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F'};
std::string result(6 * 2, ' ');
for(char& ch : result) ch = chars[std::rand() % std::size(chars)];
return result;
}
int main() {
std::srand(seed()); // seed rand()
// generate 10 mac addresses
for(int i = 0; i < 10; ++i) std::cout << GenMacAddr() << '\n';
}
That said, you could use one of the more modern pseudo random number generators, like std::mt19937, instead of rand() and use std::uniform_int_distribution instead of the modulus operation:
template<class PRNG = std::mt19937>
auto& prng() {
// same seed() function as in the previous example:
thread_local PRNG prng_instance(seed());
return prng_instance;
}
std::string GenMacAddr() {
static const char chars[] = {'0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F'};
thread_local std::uniform_int_distribution<unsigned> dist(0, std::size(chars) - 1);
std::string result(6 * 2, ' ');
for(char& ch : result) ch = chars[dist(prng())];
return result;
}
I need help to random numbers without any std-function. How can I do that? I know that I can do it with the random-function like:
v2 = rand() % 36 + 1;
which will randomize numbers between 1-35, but the rand() function belongs to the " (stdlib.h)" std.
I found similar question on stackoverflow : How do I generate random numbers without rand() function?
I make little modifications for generating between 0-35 and final solution:
#include<stdio.h>
#include<time.h>
int main()
{
int num = 36;
time_t sec;
sec=time(NULL);
for(;;)
{
sec=sec%3600;
if(num>=sec)
{
printf("%ld\n",sec);
break;
}
sec=sec%num;
}
return 0;
}
Here we are using <time.h>for time instead of <stdlib.h> for rand()
if we don't want 0 as answer then we can add
while(sec==0)
{
sec=time(NULL);
}
before this statement : sec=sec%3600;
You can use hardware random number generator:
#include <iostream>
#include "immintrin.h"
int main()
{
unsigned int val;
_rdrand32_step(&val);
std::cout << val;
}
I need to generate random Boolean values on a performance-critical path.
The code which I wrote for this is
std::random_device rd;
std::uniform_int_distribution<> randomizer(0, 1);
const int val randomizer(std::mt19937(rd()));
const bool isDirectionChanged = static_cast<bool>(val);
But do not think that this is the best way to do this as I do not like doing static_cast<bool>.
On the web I have found a few more solutions
1. std::bernoulli_distribution
2. bool randbool = rand() & 1; Remember to call srand() at the beginning.
For the purpose of performance, at a price of less "randomness" than e.g. std::mt19937_64, you can use Xorshift+ to generate 64-bit numbers and then use the bits of those numbers as pseudo-random booleans.
Quoting the Wikipedia:
This generator is one of the fastest generators passing BigCrush
Details: http://xorshift.di.unimi.it/ . There is a comparison table in the middle of the page, showing that mt19937_64 is 2 times slower and is systematic.
Below is sample code (the real code should wrap it in a class):
#include <cstdint>
#include <random>
using namespace std;
random_device rd;
/* The state must be seeded so that it is not everywhere zero. */
uint64_t s[2] = { (uint64_t(rd()) << 32) ^ (rd()),
(uint64_t(rd()) << 32) ^ (rd()) };
uint64_t curRand;
uint8_t bit = 63;
uint64_t xorshift128plus(void) {
uint64_t x = s[0];
uint64_t const y = s[1];
s[0] = y;
x ^= x << 23; // a
s[1] = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c
return s[1] + y;
}
bool randBool()
{
if(bit >= 63)
{
curRand = xorshift128plus();
bit = 0;
return curRand & 1;
}
else
{
bit++;
return curRand & (1<<bit);
}
}
Some quick benchmarks (code):
647921509 RandomizerXorshiftPlus
821202158 BoolGenerator2 (reusing the same buffer)
1065582517 modified Randomizer
1130958451 BoolGenerator2 (creating a new buffer as needed)
1140139042 xorshift128plus
2738780431 xorshift1024star
4629217068 std::mt19937
6613608092 rand()
8606805191 std::bernoulli_distribution
11454538279 BoolGenerator
19288820587 std::uniform_int_distribution
For those who want ready-to-use code, I present XorShift128PlusBitShifterPseudoRandomBooleanGenerator, a tweaked version of RandomizerXorshiftPlus from the above link. On my machine, it is about as fast as #SergeRogatch's solution, but consistently about 10-20% faster when the loop count is high (≳100,000), and up to ~30% slower with smaller loop counts.
class XorShift128PlusBitShifterPseudoRandomBooleanGenerator {
public:
bool randBool() {
if (counter == 0) {
counter = sizeof(GeneratorType::result_type) * CHAR_BIT;
random_integer = generator();
}
return (random_integer >> --counter) & 1;
}
private:
class XorShift128Plus {
public:
using result_type = uint64_t;
XorShift128Plus() {
std::random_device rd;
state[0] = rd();
state[1] = rd();
}
result_type operator()() {
auto x = state[0];
auto y = state[1];
state[0] = y;
x ^= x << 23;
state[1] = x ^ y ^ (x >> 17) ^ (y >> 26);
return state[1] + y;
}
private:
result_type state[2];
};
using GeneratorType = XorShift128Plus;
GeneratorType generator;
GeneratorType::result_type random_integer;
int counter = 0;
};
A way would be to just generate a unsigned long long for every 64 random calls as stated in the comments. An example:
#include <random>
class Randomizer
{
public:
Randomizer() : m_rand(0), counter(0), randomizer(0, std::numeric_limits<unsigned long long>::max()) {}
bool RandomBool()
{
if (!counter)
{
m_rand = randomizer(std::mt19937(rd()));
counter = sizeof(unsigned long long) * 8;
}
return (m_rand >> --counter) & 1;
}
private:
std::random_device rd;
std::uniform_int_distribution<unsigned long long> randomizer;
unsigned long long m_rand;
int counter;
};
I would prefill a (long enough) (circular) buffer of 64bit random values, and then take very quickly one bit at a time when in need of a boolean random value
#include <stdint.h>
class BoolGenerator {
private:
const int BUFFER_SIZE = 65536;
uint64_t randomBuffer[BUFFER_SIZE];
uint64_t mask;
int counter;
void advanceCounter {
counter++;
if (counter == BUFFER_SIZE) {
counter = 0;
}
}
public:
BoolGenerator() {
//HERE FILL YOUR BUFFER WITH A RANDOM GENERATOR
mask = 1;
counter = 0;
}
bool generate() {
mask <<= 1;
if (!mask) { //After 64 shifts the mask becomes zero
mask = 1;//reset mask
advanceCounter();//get the next value in the buffer
}
return randomBuffer[counter] & mask;
}
}
Of course the class can be made general to the buffer size, the random generator, the base type (doesn't necessarily have to be uint64_t) etc.
Accessing the buffer only once every 64 calls:
#include <stdint.h> //...and much more
class BoolGenerator {
private:
static const int BUFFER_SIZE = 65536;
uint64_t randomBuffer[BUFFER_SIZE];
uint64_t currValue;
int bufferCounter;
int bitCounter;
void advanceBufferCounter() {
bufferCounter++;
if (bufferCounter == BUFFER_SIZE) {
bufferCounter = 0;
}
}
void getNextValue() {
currValue = randomBuffer[bufferCounter];
bitCounter = sizeof(uint64_t) * 8;
advanceBufferCounter();
}
//HERE FILL YOUR BUFFER WITH A RANDOM GENERATOR
void initializeBuffer() {
//Anything will do, taken from here: http://stackoverflow.com/a/19728404/2436175
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<uint64_t> uni(0,std::numeric_limits<uint64_t>::max());
for (int i = 0; i < BUFFER_SIZE; i++ ) {
randomBuffer[i] = uni(rng);
}
}
public:
BoolGenerator() {
initializeBuffer();
bufferCounter = 0;
getNextValue();
}
bool generate() {
if (!bitCounter) {
getNextValue();
}
//A variation of other methods seen around
bitCounter--;
bool retVal = currValue & 0x01;
currValue >>= 1;
return retVal;
}
};
Unless you have further constraints on the randomness you need, the fastest way to generate a random bool is:
bool RandomBool() { return false; }
To be more specific, there are thousands of ways to generate random boolean numbers, all satisfying different constraints, and many of them do not deliver "truly" random numbers (that includes all the other answers so far). The word "random" alone does not tell anyone what properties you really need.
If performance is your only criterion, then the answer is:
bool get_random()
{
return true; // chosen by fair coin flip.
// guaranteed to be random.
}
Unfortunately, the entropy of this random number is zero, but the performance is quite fast.
Since I suspect that this random number generator is not very useful to you, you will need to quantify how random you want your booleans to be. How about a cycle length of 2048? One million? 2^19937-1? Until the end of the universe?
I suspect that, since you explicitly stated that performance is your utmost concern, then a good old fashioned linear congruential generator might be "good enough". Based on this article, I'm guessing that this generator's period is around 32*((2^31)-5), or about 68 trillion iterations. If that's not "good enough", you can drop in any C++11 compatible generator you like instead of minstd_rand.
For extra credit, and a small performance hit, modify the below code to use the biased coin algorithm to remove bias in the generator.
#include <iostream>
#include <random>
bool get_random()
{
typedef std::minstd_rand generator_type;
typedef generator_type::result_type result_type;
static generator_type generator;
static unsigned int bits_remaining = 0;
static result_type random_bits;
if ( bits_remaining == 0 )
{
random_bits = generator();
bits_remaining = sizeof( result_type ) * CHAR_BIT - 1;
}
return ( ( random_bits & ( 1 << bits_remaining-- ) ) != 0 );
}
int main()
{
for ( unsigned int i = 0; i < 1000; i++ )
{
std::cout << " Choice " << i << ": ";
if ( get_random() )
std::cout << "true";
else
std::cout << "false";
std::cout << std::endl;
}
}
if performance is important, perhaps it's a good idea to generate a 32 bit random number and use each separate bit of it, something like this:
bool getRandBool() {
static uint32_t randomnumber;
static int i=0;
if (i==0) {
randomnumber = <whatever your favorite randonnumbergenerator is>;
i=32;
}
return (randomnumber & 1<<--i);
}
this way the generation only impacts every 32th call
iI think that best way is an using of precalculated random array:
uint8_t g_rand[UINT16_MAX];
bool InitRand()
{
for (size_t i = 0, n = UINT16_MAX; i < n; ++i)
g_rand[i] = ::rand() & 1;
return true;
}
bool g_inited = InitRand();
inline const uint8_t * Rand()
{
return g_rand + (::rand()&INT16_MAX);
}
It using to fill some array dst[size]:
const size_t size = 10000;
bool dst[size];
for (size_t i = 0; i < size; i += INT16_MAX)
memcpy(dst + i, Rand(), std::min<size_t>(INT16_MAX, size - col));
Of course you can initialize pre-calculated array with using of another random function.
Apparently I have to add another answer. Just figured out that starting with Ivy Bridge architecture Intel added RdRand CPU instruction and AMD added it later in June 2015. So if you are targeting a processor that is new enough and don't mind using (inline) assembly, the fastest way to generate random bools should be in calling RdRand CPU instruction to get a 64-bit random number as described here (scroll to approximately the middle of the page for code examples) (at that link there is also a code example for checking the current CPU for support of RdRand instruction, and see also the Wikipedia for an explanation of how to do this with CPUID instruction), and then use the bits of that number for booleans as described in my Xorshit+ based answer.
I'm trying to find a way to find the length of an integer (number of digits) and then place it in an integer array. The assignment also calls for doing this without the use of classes from the STL, although the program spec does say we can use "common C libraries" (gonna ask my professor if I can use cmath, because I'm assuming log10(num) + 1 is the easiest way, but I was wondering if there was another way).
Ah, and this doesn't have to handle negative numbers. Solely non-negative numbers.
I'm attempting to create a variant "MyInt" class that can handle a wider range of values using a dynamic array. Any tips would be appreciated! Thanks!
Not necessarily the most efficient, but one of the shortest and most readable using C++:
std::to_string(num).length()
The number of digits of an integer n in any base is trivially obtained by dividing until you're done:
unsigned int number_of_digits = 0;
do {
++number_of_digits;
n /= base;
} while (n);
There is a much better way to do it
#include<cmath>
...
int size = trunc(log10(num)) + 1
....
works for int and decimal
If you can use C libraries then one method would be to use sprintf, e.g.
#include <cstdio>
char s[32];
int len = sprintf(s, "%d", i);
"I mean the number of digits in an integer, i.e. "123" has a length of 3"
int i = 123;
// the "length" of 0 is 1:
int len = 1;
// and for numbers greater than 0:
if (i > 0) {
// we count how many times it can be divided by 10:
// (how many times we can cut off the last digit until we end up with 0)
for (len = 0; i > 0; len++) {
i = i / 10;
}
}
// and that's our "length":
std::cout << len;
outputs 3
Closed formula for the longest int (I used int here, but works for any signed integral type):
1 + (int) ceil((8*sizeof(int)-1) * log10(2))
Explanation:
sizeof(int) // number bytes in int
8*sizeof(int) // number of binary digits (bits)
8*sizeof(int)-1 // discount one bit for the negatives
(8*sizeof(int)-1) * log10(2) // convert to decimal, because:
// 1 bit == log10(2) decimal digits
(int) ceil((8*sizeof(int)-1) * log10(2)) // round up to whole digits
1 + (int) ceil((8*sizeof(int)-1) * log10(2)) // make room for the minus sign
For an int type of 4 bytes, the result is 11. An example of 4 bytes int with 11 decimal digits is: "-2147483648".
If you want the number of decimal digits of some int value, you can use the following function:
unsigned base10_size(int value)
{
if(value == 0) {
return 1u;
}
unsigned ret;
double dval;
if(value > 0) {
ret = 0;
dval = value;
} else {
// Make room for the minus sign, and proceed as if positive.
ret = 1;
dval = -double(value);
}
ret += ceil(log10(dval+1.0));
return ret;
}
I tested this function for the whole range of int in g++ 9.3.0 for x86-64.
int intLength(int i) {
int l=0;
for(;i;i/=10) l++;
return l==0 ? 1 : l;
}
Here's a tiny efficient one
Being a computer nerd and not a maths nerd I'd do:
char buffer[64];
int len = sprintf(buffer, "%d", theNum);
Would this be an efficient approach? Converting to a string and finding the length property?
int num = 123
string strNum = to_string(num); // 123 becomes "123"
int length = strNum.length(); // length = 3
char array[3]; // or whatever you want to do with the length
How about (works also for 0 and negatives):
int digits( int x ) {
return ( (bool) x * (int) log10( abs( x ) ) + 1 );
}
Best way is to find using log, it works always
int len = ceil(log10(num))+1;
Code for finding Length of int and decimal number:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int len,num;
cin >> num;
len = log10(num) + 1;
cout << len << endl;
return 0;
}
//sample input output
/*45566
5
Process returned 0 (0x0) execution time : 3.292 s
Press any key to continue.
*/
There are no inbuilt functions in C/C++ nor in STL for finding length of integer but there are few ways by which it can found
Here is a sample C++ code to find the length of an integer, it can be written in a function for reuse.
#include<iostream>
using namespace std;
int main()
{
long long int n;
cin>>n;
unsigned long int integer_length = 0;
while(n>0)
{
integer_length++;
n = n/10;
}
cout<<integer_length<<endl;
return 0;
}
Here is another way, convert the integer to string and find the length, it accomplishes same with a single line:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
long long int n;
cin>>n;
unsigned long int integer_length = 0;
// convert to string
integer_length = to_string(n).length();
cout<<integer_length<<endl;
return 0;
}
Note: Do include the cstring header file
The easiest way to use without any libraries in c++ is
#include <iostream>
using namespace std;
int main()
{
int num, length = 0;
cin >> num;
while(num){
num /= 10;
length++;
}
cout << length;
}
You can also use this function:
int countlength(int number)
{
static int count = 0;
if (number > 0)
{
count++;
number /= 10;
countlength(number);
}
return count;
}
#include <math.h>
int intLen(int num)
{
if (num == 0 || num == 1)
return 1;
else if(num < 0)
return ceil(log10(num * -1))+1;
else
return ceil(log10(num));
}
Most efficient code to find length of a number.. counts zeros as well, note "n" is the number to be given.
#include <iostream>
using namespace std;
int main()
{
int n,len= 0;
cin>>n;
while(n!=0)
{
len++;
n=n/10;
}
cout<<len<<endl;
return 0;
}
rand() or qrand() functions generate a random int.
int a= rand();
I want to get an random number between 0 and 1.
How I can do this Work?
You can generate a random int into a float, and then divide it by RAND_MAX, like this:
float a = rand(); // you can use qrand here
a /= RAND_MAX;
The result will be in the range from zero to one, inclusive.
Using C++11 you can do the following:
Include the random header:
#include<random>
Define the PRNG and the distribution:
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0,1.0);
Get the random number
double number = distribution(generator);
In this page and in this page you can find some references about uniform_real_distribution.
Check this post, it shows how to use qrand for your purpose which is afaik a threadsafe wrapper around rand().
#include <QGlobal.h>
#include <QTime>
int QMyClass::randInt(int low, int high)
{
// Random number between low and high
return qrand() % ((high + 1) - low) + low;
}
#include <iostream>
#include <ctime>
using namespace std;
//
// Generate a random number between 0 and 1
// return a uniform number in [0,1].
inline double unifRand()
{
return rand() / double(RAND_MAX);
}
// Reset the random number generator with the system clock.
inline void seed()
{
srand(time(0));
}
int main()
{
seed();
for (int i = 0; i < 20; ++i)
{
cout << unifRand() << endl;
}
return 0;
}
Take a module from the random number which will define the precision. Then do a typecast to float and divide by the module.
float randNum(){
int random = rand() % 1000;
float result = ((float) random) / 1000;
return result;
}