In: Computer Science
( C language only )Generate a function called randomnum(n,m,neg); where n and m are the lower and upper bounds for the random number;
the generated number is negative if a variable named neg is true .These numbers should be non-zero with a maximum absolute value of 15
. You must use bitwise arithmetic to calculate the modulus of the random numbers
Code:
#include<stdio.h> // library file for standard input/output
#include<stdlib.h>
#include<stdbool.h> // very important to include if you want to pass value of neg
#include<time.h> // important for generating random numbers
int randomnum(int n,int m,bool neg){
srand(time(0)); // used to maintain uniqueness of numbers generated
int num = rand()%(m-n+1)+n; // generating a random number within (n,m)
if(num>15)return 0; // if its greater than 15, return nothing
if(neg==true){ // if neg is true, return the negative of the number
return -1*num;
}else{
return num;
}
return 0;
}
// driver code
int main(){
// generate two random numbers
int b = randomnum(5,10,false);
int c = randomnum(1,5,true);
int res = b & c; // apply bitwise & to calculate the modulus
printf("%d",c); // print the result
}
Output:
Note: Your question was a bit unclear on the bitwise part so if this what you were looking for, its all good or comment below if you need something to be changed.