Open In App

std::subtract_with_carry_engine in C++

Last Updated : 12 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The std::subtract_with_carry_engine is a random number generator engine provided by the C++ standard library. It is a template class that represents a subtract-with-carry engine which is a type of the random number generator algorithm. It is defined inside <random> header files.

Syntax

std::subtract_with_carry_engine <UIntType, w, s, r> object_name;
  • UIntType: The type of the generated random numbers often an unsigned integer type.
  • w: The number of bits in a random number. Also known as word size.
  • s: The short lag
  • r: The long lag, where 0 < s < r.

Commonly Used Functions

There are some member functions of the std::subtract_with_carry_engine which are used to perform the common operations:

S. No.

Function

Description

1

min() Used to get the minimum value that can be generated.

2

max() Used to find the maximal value that can be generated.

3

seed() The seed is used for random number generation.

4

operator () The operator () is overloaded to return the randomly generated number.

Examples

Example 1: Generating 2 Numbers and Comparing Them.

C++




// C++ Program to illustrate std::subtract_with_carry_engine
#include <iostream>
#include <random>
  
using namespace std;
  
int main()
{
    // creating engine object
    subtract_with_carry_engine<unsigned int, 29, 19, 24>
        engine;
  
    // generating two random numbers
    unsigned int random1 = engine();
    unsigned int random2 = engine();
  
    // comparing numbers
    if (random1 > random2) {
        cout << "random1 is greater than random2" << endl;
    }
    else if (random1 < random2) {
        cout << "random2 is greater than random1" << endl;
    }
    else {
        cout << "random1 is equal to random2" << endl;
    }
    return 0;
}


Output

random2 is greater than random1

Example 2: Generating 10 Random Numbers One by One.

C++




// C++ Program to illustrate std::subtract_with_carry_engine
#include <iostream>
#include <random>
  
using namespace std;
  
int main()
{
    // Create an engine with the specified parameters
    subtract_with_carry_engine<uint_fast32_t, 31, 7, 11>
        engine;
  
    // Generating 10 random numbers
    for (int i = 0; i < 10; ++i) {
        uint_fast32_t random_value = engine();
        cout << "The Random Number: " << random_value
             << endl;
    }
    return 0;
}


Output

The Random Number: 1610992232
The Random Number: 1225659571
The Random Number: 1456584671
The Random Number: 1071764482
The Random Number: 333868461
The Random Number: 2064876693
The Random Number: 1689989734
The Random Number: 1479050034
The Random Number: 205186667
The Random Number: 506270897


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads