This code is supposed to generate random number between 1 to 10, but it returns 1 every time.
int random_integer;
int lowest=1, highest=10;
int range=(highest-lowest)+1;
random_integer = lowest + int(range*rand()/(RAND_MAX + 1.0));
cout << random_integer << endl;
What's wrong in the code?
If you want a random integer between lowest and highest, you'd better write
random_integer = lowest + rand() % range
You're subject to overflow here - range*rand().
Just use what regular folks use: rand() % 10 + 1.
range * rand() / (RAND_MAX + 1.0)
does not do what you think. Introduce some parens:
range * (rand() / (RAND_MAX + 1.0))
(Note that this method gives skewed distributions, though.)
I agree with all the solution provided above .
now to get a different sequence every time you run your program you can use srand() function it will provide a seed to rand() function as follows:-
srand(time(NULL))
random_integer = lowest + rand() % range
This two are always part of my programs
float randf(float lo, float hi) {
float random = ((float) rand()) / (float) RAND_MAX;
float diff = hi - lo;
float r = random * diff;
return lo + r;
}
int randi(int lo, int hi)
{
int n = hi - lo + 1;
int i = rand() % n;
if (i < 0) i = -i;
return lo + i;
}
You seem to assume that rand() returns a value between 0 and 1.
This is not correct, it return value between 0 and RAND_MAX.
Related
float genData(int low, int high);
int main(){
srand(time(0));
float num = genData(40, 100);
cout << fixed << left << setprecision(2) << num << endl;
return 0;
}
float genData(int low, int high) {
low *= 100;
high *= 100 + 1;
int rnd = rand() % (high - low) + low;
float newRand;
newRand = (float) rnd / 100;
return newRand;
}
I'm expecting a random number between 40 and 100 inclusively with two decimal places.
eg: 69.69, 42.00
What I get is the same number with different decimal values, slowly increasing every time I run the program.
Use the <random> header for that:
#include <iostream>
#include <random>
float getData(int const low, int const high) {
thread_local auto engine = std::mt19937{ std::random_device{}() };
auto dist = std::uniform_int_distribution<int>{ low * 100, high * 100 };
return dist(engine) / 100.0f;
}
int main() {
for (auto i = 0; i != 5; ++i) {
std::cout << getData(40, 100) << '\n';
}
}
Wrong range
int rnd = rand() % (high - low) + low; does not generate the right range.
float genData(int low, int high) {
low *= 100;
// high *= 100 + 1;
high = high*100 + 1;
expecting a random number between 40 and 100 inclusively with two decimal places. eg: 69.69, 42.00
That is [40.00 ... 100.00] or 10000-4000+1 different values
int rnd = rand() % (100*(high - low) + 1) + low*100;
float frnd = rnd/100.0f;
rand() weak here when RAND_MAX is small
With RAND_MAX == 32767, int rnd = rand() % (high - low) + low; is like [0... 32767] % 6001 + 40000. [0... 32767] % 6001 does not provide a very uniform distribution. Some values coming up 6 times and others 7-ish.
If you are using C++ 11 you can use better random number generators that will give you diversity in the generated numbers in addition to being a lot faster.
Quick Example:
#include <random> // The header for the generators.
#include <ctime> // To seed the generator.
// Generating random numbers with C++11's random requires an engine and a distribution.
mt19937_64 rng(seed);
// For instance, we will create a uniform distribution for integers in the (low, high) range:
uniform_int_distribution<int> unii(low, high);
// Show the random number
cout << unii(rng) << ' ';
You can follow this article for more explanation from here.
The following code is a solution to a problem statement from a contest.
The time constraint given was 1s. The code worked correctly for 5/7 test cases. For the rest cases, the time limit was exceeded.
How can the time complexity for the code below be reduced?
Edit:
The problem statement is defined as return the value of number n or sum of n/2,n/3,n/4 whichever is maximum.
For example, if input is 24
it can be reduced or exchanged for
12+8+6=26
Further, 12 can be reduced to 6+4+3=13.
8 and 6 should not be reduced as it may decrease the value.
So final answer is 13+8+6=27
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#define lli long long int
using namespace std;
lli exchange(lli n){
if(n<12)
return n;
else{
lli sum=0;
sum+=max(n/2,exchange(n/2));
sum+=max(n/3,exchange(n/3));
sum+=max(n/4,exchange(n/4));
return sum;
}
}
int main() {
lli t;
cin>>t;
while(t--){
lli n;
cin>>n;
lli ans;
ans=max(n,exchange(n));
cout<<ans<<endl;
}
return 0;
}
Just trying some ideas out. First, the "true" branch of an if-statement is the branch that the compiler pre-loads instructions on. By making the high-n branch the default, it's a little faster.
EDITED: Some of the other ideas didn't work out (no faster). However, one that is promising is to unroll two levels of the recursion.
exchange(n) = exchange(n/2) + exchange(n/3) + exchange(n/4)
exchange(n/2) = exchange(n/2/2) + exchange(n/3/2) + exchange(n/4/2)
exchange(n/3) = exchange(n/2/3) + exchange(n/3/3) + exchange(n/4/3)
exchange(n/4) = exchange(n/2/4) + exchange(n/3/4) + exchange(n/4/4)
However, these become untrue if n/4 < 12. So we can unroll one full level of recursion and only use the fallback for n < 48. Here's an "opt" version of exchange:
lli exchange_opt(lli n)
{
if (n >= 12 * 4) // for n=48+ none of the terms would trigger n < 12
{
lli sum = 0;
sum += exchange_opt(n / 4);
sum += exchange_opt(n / 6) * 2;
sum += exchange_opt(n / 8) * 2;
sum += exchange_opt(n / 9);
sum += exchange_opt(n / 12) * 2;
sum += exchange_opt(n / 16);
return sum;
}
if (n > 11)
{
lli sum = 0;
sum += exchange_opt(n / 2);
sum += exchange_opt(n / 3);
sum += exchange_opt(n / 4);
return sum;
}
return n;
}
this is 4 times faster on my machine than the default implementation, and the idea is extensible, e.g. you could unroll three levels of recursion, but increase the n-count at which it applies. Here's a version which unrolls three levels of recursion from the base case, and combines like terms to reduce function calls. It's 8 times faster now:
lli exchange_opt(lli n)
{
if (n >= 12 * 4 * 4)
// for n=48+ none of the core terms would trigger n < 12
{
lli sum = 0;
sum += exchange_opt(n / 8);
sum += exchange_opt(n / 12) * 3;
sum += exchange_opt(n / 16) * 3;
sum += exchange_opt(n / 18) * 3;
sum += exchange_opt(n / 24) * 6;
sum += exchange_opt(n / 27);
sum += exchange_opt(n / 32) * 3;
sum += exchange_opt(n / 36) * 3;
sum += exchange_opt(n / 48) * 3;
sum += exchange_opt(n / 64);
return sum;
}
if (n >= 12 * 4)
// for n=48+ none of the core terms would trigger n < 12
{
lli sum = 0;
sum += exchange_opt(n / 4);
sum += exchange_opt(n / 6) * 2;
sum += exchange_opt(n / 8) * 2;
sum += exchange_opt(n / 9);
sum += exchange_opt(n / 12) * 2;
sum += exchange_opt(n / 16);
return sum;
}
if (n >= 12)
{
lli sum = 0;
sum += exchange_opt(n / 2);
sum += exchange_opt(n / 3);
sum += exchange_opt(n / 4);
return sum;
}
return n;
}
BTW for testing, i ran all the numbers from 0 ... 9999 through the system, then added up the time for the OP's original function and my functions, while testing that the results were equal. As this is optimized for large numbers, the results might be even better on very large numbers.
I'm guessing that every level of recursion that's unrolled will roughly double the speed of this algorithm. Instead of computing the unrolling by hand as I have done, it might actually be possible to write a program that outputs the correct equation for the level of unrolling needed. Basically to compute exchange(n) in the minimum time you want to unroll to the nearest level of recursion "k" where n >= 12 * 4^k
But enough of manually unrolling the loop. Here's a recursive function that generates the recursive function to whatever level of unrolling needed. it uses std::vector, std::map so you'll need to include the right headers:
std::vector<std::map<lli, lli>> map1;
map1.push_back(std::map<lli, lli>());
map1[0][2] = 1;
map1[0][3] = 1;
map1[0][4] = 1;
const int unrolled_levels = 20;
for (int level = 1; level < unrolled_levels; ++level)
{
map1.push_back(std::map<lli, lli>());
for (auto i = map1[level - 1].begin(); i != map1[level - 1].end(); ++i)
{
map1[level][(*i).first * 2] += map1[level - 1][(*i).first];
map1[level][(*i).first * 3] += map1[level - 1][(*i).first];
map1[level][(*i).first * 4] += map1[level - 1][(*i).first];
}
}
int level = unrolled_levels - 1;
std::cout << "\tlli exchange_opt(lli n) // unroll" << level << "\n\t{\n\n";
for (int inner_level = level; inner_level >= 0; --inner_level)
{
lli mult = 12;
std::cout << "\t\tif (n >= 12LL ";
for (auto i = 0; i < inner_level; ++i)
{
std::cout << " * 4LL";
mult *= 4LL;
}
std::cout << ") // " << (mult) << "\n\t\t{\n";
std::cout << "\t\t\tlli sum = 0;\n";
for (auto i = map1[inner_level].begin(); i != map1[inner_level].end(); ++i)
{
std::cout << "\t\t\tsum += exchange_opt(n/" << (*i).first << "LL)";
if ((*i).second > 1) std::cout << " * " << (*i).second;
std::cout <<"; \n";
}
std::cout << "\t\t\treturn sum;\n";
std::cout << "\t\t}\n";
}
std::cout << "\t\treturn n;\n";
std::cout << "\n\t}\n\n";
Basically, you set unrolled_levels to whatever you want. Each level unrolls the equation for 4 time bigger numbers. Just be aware that the output function is going to be huge, it tests the number range for n and then proceeds to short-circuit the sub-levels as much as possible. For some higher numbers it works out a partial value and mults by thousands or millions, effective short-circuiting millions of function calls.
Copy and paste the output from this code and use it as the function for calculating exchange(n). For numbers around 1 million, it's 200 times faster than the original formula (0.5% running time). For numbers around 100 million, it took 1/70 of 1% of the original equation, 7000 times faster.
BTW this could be even faster. I haven't gone through and collected terms which are multiplied by like-constants in the same branch.
One of the standard trade-offs in any algorithm is time vs. space; the more memory or disk space you have, the more time you can save, or vice versa. In this case, you need to run within a specific time, but you appear to be allowed to use the full memory of the machine. Therefore, noting that this particular algorithm frequently requests values that it has already calculated, it should be worth saving them all for quick lookup.
Indeed, Python, not often regarded as particularly fast, can calculate 10295 in about a second, though 10300 runs into a maximum recursion depth error if run with an empty result cache:
exchanged = {}
def exchange(n):
if n in exchanged:
value = exchanged[n]
elif n < 12:
exchanged[n] = value = n
else:
exchanged[n] = value = exchange(n//2) + exchange(n//3) + exchange(n//4)
return value
exchange(10**295)
For C++, a static std::map<lli, lli> should work for in place of the exchanged dict. Don't try using an array, though, because you don't need nearly as many values as the largest one calculated; 10295, for example, uses less than 300,000 results.
And yes, the max part can be omitted, because it's handled by the n < 12 check. We can prove this by noting that it would only be necessary if (n-1)/2 + (n-2)/3 + (n-3)/4 < n (accounting for the way integer division throws away the remainder), throwing out all cases above 23; the remaining cases are easy to check by hand, and the largest exception happens to be 11. But that's a minor optimization compared with changing your algorithm from O(n*log(n)) to O(log(n)).
I have found a formula that solves a problem but I can't make it work for large numbers. The n-th factor would be the (n-1)-th factor + (n-1)*(n-1) + n * n
So I wrote this function:
inline long long int formula(long long int n)
{
if(n==1)return 1;
return formula(n-1)+(n-1)*(n-1)+*n*n;
}
and since the answer has to be calculated modulo 666013, I added this (MOD=666013):
inline long long int formula(long long int n)
{
if(n==1)return 1;
return ((formula(n-1)%MOD+(1LL*(n-1)*(n-1))%MOD)%MOD+(1LL*n*n)%MOD)%MOD;
}
I probably didn't use modulo correctly. My function has to work for numbers as large as 2.000.000.000 and it stops working at about 30.000
EDIT: I've tried using a loop and I still can't make it work for numbers larger than 20.000.000. This is what I'm using:
ans=1;
for(i=2;i<=n;i++)
{
ans=(ans%MOD+1LL*(i-1)*(i-1)%MOD+1LL*i*i%MOD)%MOD;
}
I don't understand why you are using a recursive function for this. It will work at a low number of calls, but if you recursively call it a few milion times, well... it will not. The reason is that you are calling a function within another function within another function... too many times provoking the program to collapse or named as "Stack Overflow".
The best possible way to overcome this, is to use a loop to fix it up! Just iterate from 0 to n (n being the number you want to obtain).
Simplify as much as possible in order to be able to see the requirements:
typedef long long val_t;
#define MOD ((val_t) 666013)
// for really big numbers, change #if to 1
#if 0
#define MODOF(_x) ((_x) % MOD)
#else
#define MODOF(_x) (_x)
#endif
#define SQR(_i) MODOF((_i) * (_i))
val_t
formula(val_t n)
{
val_t i;
val_t ans;
ans = 0;
for (i = 1; i <= n; ++i) {
ans += SQR(i-1);
ans += SQR(i);
ans %= MOD;
}
return ans;
}
UPDATE: I'm so used to seeing factorial herein that I wrote the wrong formula. Now corrected.
Iterative version of your code is in below . You can use it
inline long long int formula(long long int n)
{
long long f = 1;
for (int i = 2; i <= n; i++)
{
f = ((f % MOD + (1LL * (i - 1)*(i - 1)) % MOD) % MOD + (1LL * i*i) % MOD) % MOD;
}
return f;
}
The loop will take quite a long time if you need to calculate it for size of 2 billion. However, the recursive equation leads trivially to
sum [i * i+(i-1)*(i-1)] = sum [2* i * i - 2*i + 1].
You can use the equation for the sum of first n squares and the arithmetic sequence to simplify this to:
2*n(n * n + 1) / 3
Now you can further reduce this using a * b % c = (a % c) * (b %c). However, the division by 3 and modulus operation does not commute. So you need to write the equation as
( ((2*(n % MOD)) %MOD) * (((n % MOD) * (n % MOD)) +1) %MOD) * 444009) % MOD,
where the 444009 is the modular inverse of 3 mod MOD, i.e, 3*444009 % MOD =1.
EDIT: Added the discussion about commuting modulus and division operators as pointed out by Raymond Chen the modulus and division do not commute.
roommate went to an interview and got this one:
Rules:
permitted to use rand();
RAND_MAX = 32 767;
no use of division or modulo;
TODO:
Write a function that takes one int parameter and returns
int in range 0 - parameter.
Head hurts, can't sleep. Any help appreciated.
Thanks
Few possibilities:
the range transposition approach: int r = rand() * 0.00003051855095 * n;
the "shuffle sort" approach: int r; do { r = random(); } while (r >= n);
the BSD approach: uint32_t r = arc4random_uniform(n);
Etc., etc., etc.
In my public domain randlib, I do it with
no floating point, no division, no multiplication, just bitmasking and rejection sampling, like this:
int ojr_rand(ojr_generator *g, int limit) {
int v, m = limit - 1;
m |= m >> 1;
m |= m >> 2;
m |= m >> 4;
m |= m >> 8; // m is smallest ((power of 2) - 1) > limit
do {
v = m & NEXT16(g); // 16-bit random number
} while (v >= limit);
return v;
}
In the worst case (limit is power of two plus one), this can reject close to 50% of the generated numbers, but it's still faster than division or floating math with most fast RNGs, and in the general case it's much faster. Also, unlike the floating point math or mod, it is exact, meaning if you ask for a limit of 3, you get values 0, 1, and 2 with exactly equal probability, not just approximately equal.
If c++11 is allowed there is a random header provided that makes this trivial:
#include <random>
#include <iostream>
int Roll(int Max)
{
if(Max>32767)
Max=32767;
std::random_device generator;
std::uniform_int_distribution<int> distribution(0,Max);
return distribution(generator);
}
int main()
{
std::cout << Roll(10) << std::endl
<< Roll(10) << std::endl
<< Roll(999999) << std::endl;
}
More details at: http://en.cppreference.com/w/cpp/numeric/random
This presumes that RAND_MAX is provided by your problem and not by the C standard of course you could use the provided constant, for details see: http://en.cppreference.com/w/cpp/numeric/random/RAND_MAX
do { r = random();} while (r >= max_rand);
At first I thought multiplying by a fraction would work but that could be considered cheating from a mathematical standpoint.
int getRand(int max)
{
int val = rand();
while (val > max)
{
val -= max + 1;
}
return val;
}
This will obviously be off slightly by counting values <= RAND_MAX % max once more than everything else but rand() % max has the same problem so I assume this error to be acceptable (for values of max << MAX_RAND the error is insignificant).
I know this is a rather simple question, but I'm just not too good at maths.
I know how to generate a random float between 0 and 1:
float random = ((float) rand()) / (float) RAND_MAX;
But what, if I want a function that given a range of two floats, returns a pseudorandom float in that range?
Example:
RandomFloat( 0.78, 4.5 ); //Could return 2.4124, 0.99, 4.1, etc.
float RandomFloat(float a, float b) {
float random = ((float) rand()) / (float) RAND_MAX;
float diff = b - a;
float r = random * diff;
return a + r;
}
This works by returning a plus something, where something is between 0 and b-a which makes the end result lie in between a and b.
float RandomFloat(float min, float max)
{
// this function assumes max > min, you may want
// more robust error checking for a non-debug build
assert(max > min);
float random = ((float) rand()) / (float) RAND_MAX;
// generate (in your case) a float between 0 and (4.5-.78)
// then add .78, giving you a float between .78 and 4.5
float range = max - min;
return (random*range) + min;
}
Random between 2 float :
float random_between_two_int(float min, float max)
{
return (min + 1) + (((float) rand()) / (float) RAND_MAX) * (max - (min + 1));
}
Random between 2 int :
int random_between_two_int(float min, float max)
{
return rand() % (max - min) + min + 1;
}
Suppose, you have MIN_RAND and MAX_RAND defining the ranges, then you can have the following:
const float MIN_RAND = 2.0, MAX_RAND = 6.0;
const float range = MAX_RAND - MIN_RAND;
float random = range * ((((float) rand()) / (float) RAND_MAX)) + MIN_RAND ;
This will provide you the number scaled to your preferred range.
MIN_RAND, MAX_RAND can be any value, like say 2.5, 6.6
So, the function could be as:
float RandomFloat(float min, float max) {
return (max - min) * ((((float) rand()) / (float) RAND_MAX)) + min ;
}