Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ เพื่อสร้างตัวเลขสุ่มโดยใช้วิธี Middle Square


วิธีกำลังสองกลางเป็นหนึ่งในวิธีที่ง่ายที่สุดในการสร้างตัวเลขสุ่ม วิธีนี้จะเริ่มสร้างหมายเลขเดิมซ้ำๆ หรือวนซ้ำเป็นหมายเลขก่อนหน้าในลำดับและวนซ้ำไปเรื่อยๆ สำหรับตัวสร้างตัวเลขสุ่ม ndigit ระยะเวลาต้องไม่เกิน n หากเลขกลาง n ตัวเป็นศูนย์ทั้งหมด เครื่องกำเนิดจะแสดงผลค่าศูนย์ตลอดไป ในขณะที่การรันค่าศูนย์เหล่านี้ตรวจได้ง่าย แต่เกิดขึ้นบ่อยเกินไปสำหรับวิธีนี้ที่จะนำไปใช้ได้จริง

Input − Enter the digit for random number:4
Output − The random numbers are: 6383, 14846, 8067, 51524, .........

อัลกอริทึม

Begin
   middleSquareNumber(number, digit)
   Declare an array and assign next_number=0.
   Square the number and assign it to a variable sqn.
   Divide the digit by 2 and assign it to a variable t.
   Divide sqn by a[t] and store it to sqn.
   For i=0 to digit, do
      next_number =next _number (sqn mod (a[t])) * (a[i]);
      sqn = sqn / 10;
   Done
   Return the next number
End.

โค้ดตัวอย่าง

#include <iostream>
using namespace std;
int a[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 };
int middleSquareNumber(int number, int digit) {
   int sqn = number * number, next_number = 0;
   int t = (digit / 2);
   sqn = sqn / a[t];
   for (int i = 0; i < digit; i++) {
      next_number += (sqn % (a[t])) * (a[i]);
      sqn = sqn / 10;
   }
   return next_number;
}
int main(int argc, char **argv) {
   cout << "Enter the digit random numbers you want: ";
   int n;
   cin >> n;
   int start = 1;
   int end = 1;
   start = a[n - 1];
   end = a[n];
   int number = ((rand()) % (end - start)) + start;
   cout << "The random numbers are:\n" << number << ", ";
   for (int i = 1; i < n; i++) {
      number = middleSquareNumber(number, n);
      cout << number << ", ";
   }
   cout << ".........";
}

ผลลัพธ์

Enter the digit random numbers you want: 4
The random numbers are: 6383, 14846, 8067, 51524, .........