The 3n+1 Problem of algorithm

Source: Internet
Author: User
Tags floor function

Karaz (Callatz) conjecture:

For any natural number n, if it is even, cut it in half, and if it is odd, cut it off by half (3n+1). This has been repeatedly cut down, and finally must be in a certain step to get n=1. Karaz at the 1950 World Mathematicians conference published this conjecture, the legend of Yale University teachers and students to mobilize, desperately want to prove this seemingly silly very naïve proposition, the result of students do not want to study, the only card (3n+1), so that some people say this is a conspiracy, Karaz is deliberately delaying the progress of teaching and research in the American mathematical world ...

conjecture content: for any natural number greater than 1 N, if n is odd, then n becomes 3n+1, otherwise becomes half of N. after a number of such transformations, the n will be changed to 1. such as 3->10->5->16->8->2->1.
Enter N, the number of times the transformation is output. N≤10^9.
Example input: 3
Sample output: 7 (some blog output is 5 is considered the number of changes here is to each occurrence of the count as one)

#include <stdio.h>
int main (void)
{
int n;
int count=0;
scanf ("%d", &n);
while (n > 1)
{
if (n%2! = 0)
n = 3*n + 1;
Else
n/= 2;
count++;
}
printf ("%d\n", count);
return 0;
}

However, is the procedure correct? Unfortunately, if you enter 987654321, the answer is 1, which is obviously wrong. by debugging or printing the value of n in the loop body with a printf statement, you see that the value of n is negative, causing the program to exit after a single loop. From here we can learn that the value of n overflows because the integer maximum value is 2^31-1 = 2147483647, approximately 2.1 billion, and the maximum value of test instructions n is 1 billion (10^9), so it is dangerous to multiply the value of N by 3, which can cause overflow.

The solution is as follows:

Because odd * odd = odd, so after n=3*n+1 calculation, the value of n is necessarily an even number, and the next cycle must do the operation n/=2, so here can merge these two steps, that is, n is an odd case to do the operation N=floor (1.5*n+0.5), Because of the error problem of double value, we can use N=floor (1.5*n+1) (floor function to receive a double type parameter, return the maximum number of shapes not greater than the given parameter, the return value type is double), Assigns the integer double value to shaping to discard the decimal point.

#include <stdio.h>#include<math.h>intMainvoid){    intN; intCount=0; scanf ("%d", &N);  while(N >1)    {          if(n%2!=0) {n= Floor (1.5*n +1); Count+=2; }        Else{n= N/2; Count++; }} printf ("%d\n", Count); return 0;}

The correct result can also be calculated using a long long version

#include <stdio.h>intMain () {intN2; intCount=0; scanf ("%d", &n2); Long Longn =N2;  while(N >1)    {          if(n%2!=0) n= n *3+1; ElseN= N/2; Count++; } printf ("%d\n", Count); return 0;}

Reference: "Algorithmic Competition Primer Classic"--Rujia

Experience:

1. C99 supports defined variables within a for loop ()

2. while (scanf ("%d%d", &begin,&end)!=eof);

Finally some doubts (see the Master can answer one or two, I will be greatly appreciated):

1, here is the second program I wrote according to the author's tips, I think it should be correct:-), but there are some doubts, such as we consider the first n input value, but the loop

The second time, the third ... How do we explain that the value of the loop will not overflow in the future?

For example, when the value of n at the beginning is 7, then the value of the loop is 11, and 11>7. This means that the value of the two cycles is greater than 7.

2, moreover, how do we know that after a number of transformations will be 1, that is to say how we know the function convergence? Well... It seems to be a mathematical problem.

The answer to this question I was in the math science god Ben Gusen blog found, its blog address here Matrix67 (by the way, very good blog), the original see here do not learn mathematics: the most torture of the mathematical unsolved Mystery (a), the following text extracts related to the question here:

The beauty of mathematics is not only reflected in the beautiful conclusions and subtle proofs, but also the unsolved problems of mathematics are fascinating. Unlike the Goldbach conjecture and Riemann hypothesis, some of the unresolved problems are interesting and "mathematically" very weak, at first glance it does not seem to touch the profound mathematical theory
Seems to be a mathematical puzzle that can be killed in seconds, so that math enthusiasts "don't find a clever solution", but surprisingly, they are no less difficult than well-known mathematical speculations, which may be more problematic than difficult math puzzles in every field. As a set of mathematical interest, mathematical puzzles in a book to the still unresolved math puzzles in a separate chapter, it can be seen how fascinating these problems. I have selected some questions from this chapter to share with you here. This book isGenevaPublished in the year,
Some of the "latest developments" mentioned in the book are not up to date, but I have not examined the current progress of each issue, so the information in this article is not guaranteed to be -%accurate, apologize to the readers here. 3x+1Problem
Start with any positive integer and repeat the following: If the number is even, divide it by2If the number is odd, expand it to the original3Times and then add1。 Will the sequence eventually become4,2,1,4,2,1,... The loop? This question can be said to be a
"Pit"-at first glance, the problem is very simple, a lot of breakthroughs, so the mathematicians jumped into the inside, but it is easy to go out, many mathematicians to death did not put this problem out. Countless mathematicians have been recruited, which can be from 3x+1The various aliases of the problem are shown: 3x +1The problem is also called
Collatz conjecture, Syracuse problem, Kakutani problem, Hasse algorithm, Ulam problem and so on. Later, because of the name controversy too big, simply let no one dipping, directly called 3x +1question. 3x+1The problem is not a general difficulty. Here's an example to show how irregular the sequence of the series converges. From -Start Counting,TenStep fell into the "421trap ": -, -, +, -,Ten,5, -,8,4,2,1,4,2,1,... However, from -At first, the numbers soar to over thousands of, and you're likely to think it's out of the "421trap "; But, after hundreds of steps, it fell back: -, the, A,124, +, to,94, -,142, in,214,107,322,161,484,242,121,364,182, the,274,137,412,206,103,310,155,466,233, the, -,175,526,263,790,395,1186,
593,1780,890,445,1336,668,334,167,502,251,754,377,1132,566,283,850,425,1276,638,319,958,479,1438,719,2158,1079,3238,1619,4858,2429,7288,3644,1822,
911,2734,1367,4102,2051,6154,3077,9232,4616,2308,1154,577,1732,866,433,1300,650,325,976,488,244,122, A,184, the, $, at, -, *,106, -, the, the, +,
-,Ten,5, -,8,4,2,1,4,2,1, ...

Extra, another point: As mentioned above, since the convergence of the sequence is so irregular, then our program above may be wrong (including the one after optimization). For example, let's do a test with a long long int:

#include <math.h>intMainvoid){    Long Long intN; intCount=0;//number of statistical calculationsscanf ("%i64d", &n);//long Long int must read the data with%i64d in Windows, otherwise it will be a problem (such as data truncation, etc.)    Long LongMax =0;//record the maximum value that occurs during the calculation         while(N >1)    {        if(n%2!=0)        {            //n = Floor (1.5*n + 1);n = n *3+1; }        Else{n= N/2; } Count++; printf ("%i64d\n", n);//The output also uses%i64d                if(N >max) Max=N; } printf ("%d\n%i64d\n", Count, Max); return 0;}

We enter 704511, the output of the last printf function: 242,56991483520. It can be seen that the median value is 50 billion so large, and the n = floor (1.5*n + 1) statement instead of n = n * 3 + 1, the middle value of the output is 28495741760, also 20 billion is so large, the int type cannot hold such a large data, so the previous two programs in the case of insufficient testing strength of the surface It's right to look at it, but it's wrong.
Finally, the writing here, should be able to come to an end.

Transferred from: http://www.cnblogs.com/xpjiang/p/4129340.html

The 3n+1 Problem of algorithm

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.