This C program generates random numbers using middle square method. In mathematics, the middle-square method is a method of generating ‘pseudorandom’ numbers.To generate a sequence of 4-digit pseudorandom numbers, a 4-digit starting value is created and squared, producing an 8-digit number (if the result is less than 8 digits, leading zeroes are added to compensate). The middle 4 digits of the result would be the next number in the sequence, and returned as the result. This process is then repeated to generate more numbers.
Here is the source code of the C program to generate random numbers of desired length using Von Neumann middle square method. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
unsigned long long int randm(int n);
unsigned long long int von(unsigned long long int x, int n);
int main(void)
{
unsigned long long int x, s;
int n, i, r;
printf("Enter the number of digits in the seed value ");
scanf("%d", &n);
printf("\nEnter the total number of random numbers to be generated ");
scanf("%d", &r);
if (n >= 12){
printf("TOO LARGE!!");
exit(0);
}
x = randm(n);
for(i = 0; i < r; i++){
s = von(x, n);
x = s;
printf("\nRandom Number generated: %lld\n", s);
}
return 0;
}
/*Generating Random Number of desired digit*/
unsigned long long int randm(int n)
{
double x;
unsigned long long int y;
srand(getpid());
x = rand() / (double)RAND_MAX;
y = (unsigned long long int) (x * pow(10.0, n*1.0));
return y;
}
/*Calculating Random Number By Von Neumann Middle Square method*/
unsigned long long int von(unsigned long long int x, int n)
{
unsigned long long int y;
int k;
k = n / 2;
y =(unsigned long long int)((x / pow(10.0, k * 1.0)) * x) % (unsigned long long int) (pow(10.0, n * 1.0));
return y;
}
$ gcc middle_square_method.c -o middle_square_method $ ./middle_square_method Enter the number of digits in the seed value 11 Enter the total number of random numbers to be generated 4 Random Number generated: 89135450408 Random Number generated: 85194370272 Random Number generated: 7260426368 Random Number generated: 37910451496
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Next Steps:
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Practice BCA MCQs
- Apply for Computer Science Internship
- Apply for C Internship
- Practice Computer Science MCQs
- Buy C Books