Random Number problem-it is known that there is a Random7 () function, returns a random natural number from 1 to 7, so that the Random7 () is used to construct a random 1 ~ Random10 ~ 10. random7random10

Source: Internet
Author: User
Tags float number

Random Number problem-it is known that there is a Random7 () function, returns a random natural number from 1 to 7, so that the Random7 () is used to construct a random 1 ~ Random10 ~ 10. random7random10

Math. random () randomly generates the float number between (0, 1), and Random7 randomly generates an integer between [1, 7], and uses Random7 to construct Random10:

1. Generate a: a is the result of two Random7 requests, that is, a = (Random7 ()-1) * 7 + Random7 ()-1;

2. judge whether a is less than 40. If it is less than 40, return a/4 + 1, that is, the final result; otherwise, continue to execute Random10;

Public class B
{
Public static int Random7 (){
Return (int) (Math. random () * 7 + 1 );
}
Public static int Random10 (){
Int a = 49;
While (a> = 40 ){
A = (Random7 ()-1) * 7 + Random7 ()-1;
}
Return a/4 + 1;
}
Public static void main (String [] args)
{
For (int I = 0; I <50; I ++ ){
System. out. println (Random10 ());
}
}
}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.