100-The 3N + 1 problem

Source: Internet
Author: User

A simple question can be directly simulated according to the question requirements. Note that the intermediate results can be saved to increase the running time by an order of magnitude.

There should be a faster method, but for the scale given in this question, thisAlgorithmThe results can be obtained quickly.

 

Returns the volume I index.

Returns the total index.

 

// 100_3n_plus_1.cpp: defines the entry point for the console application. <br/> // </P> <p> # include <math. h> </P> <p> # ifndef online_judge <br/> # include <fstream> <br/> STD: ifstream CIN ("in.txt "); <br/> STD: ofstream cout ("out.txt "); <br/> # else <br/> # include <iostream> <br/> # endif </P> <p> using namespace STD; </P> <p> # define Max 1000000 <br/> int * seqlen; </P> <p> int getseqlen (int x) <br/> {<br/> If (seqlen [x]> 0) <br/>{< br/> return seqlen [X]; <br/>}</P> <p> int nseq = 1; </P> <p> int y = x; <br/> while (X! = 1) <br/>{< br/> If (x <= max & seqlen [x]> 0) <br/>{< br/> nseq + = (seqlen [x]-1); <br/> break; <br/>}</P> <p> If (X % 2 = 0) <br/>{< br/> X/= 2; <br/>}< br/> else <br/> {<br/> X = 3 * x + 1; <br/>}</P> <p> ++ nseq; <br/>}</P> <p> seqlen [y] = nseq; </P> <p> return nseq; <br/>}</P> <p> int getmax (int I, Int J) <br/> {<br/> int base = I <= J? I: J; <br/> int bound = I >= J? I: J; </P> <p> int Nmax = 0; <br/> int nlen = 0; </P> <p> for (INT x = base; x <= bound; ++ X) <br/>{< br/> nlen = getseqlen (x); <br/> If (nlen> Nmax) <br/>{< br/> Nmax = nlen; <br/>}</P> <p> return Nmax; <br/>}</P> <p> int main () <br/> {<br/> seqlen = new int [Max + 1]; </P> <p> memset (seqlen, 0, sizeof (INT) * (MAX + 1); </P> <p> int I, J; </P> <p> while (CIN> I> J) <br/> {<br/> cout <I <''<j <'' <getmax (I, j) <'/N '; <br/>}</P> <p>

 

100-The 3N + 1 problem

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.