Wednesday 15 June 2011

java - Use of integers and doubles give different answers when they shouldn't -


I am resolving a project using Java. I am not asking for help in solving the problem. I have already solved it, but I have something I can not understand.

The problem is similar:

The following repeated sequence set is defined for positive integers:

n = n / 2, if N is also n, then n = 3n + 1, if n is weird

Using the above rule and starting with 13, we generate the following sequence:

13 - Gt; 40 - & gt; 20 - & gt; 10 - & gt; 5 - & gt; 16 - & gt; 8 - & gt; 4 - & gt; 2 - & gt; 1. Here, the length of the series is 10 numbers.

Find the starting number starting at 1,000,000 which creates the longest chain.

Then I wrote this code:

  public class Euler014 {public static zero main (string [] args) {int maxChainCount = 0; Integer = 0; Int n; Int chainCount = 1; For (Int i = 0; I <1000000; i ++) {n = i; While (n> 1) {if (n% 2 == 0) {// even if check n / = 2; } And {// and: odd n = 3 * n + 1; } Chancount ++; } If (Chancet> Maximum ChainConnect) // Check whether this is the longest series ever, maxChainCount = chainCount; Answer = i; } Chancet = 1; } System.out.println ("\ n \ nLong series: i =" + answer); }}   

This gives me the answer 910107, which is wrong.

However, if I type my n variable type double n it runs and gives me 8377 9 9, which is correct!

This really confuses me, because I do not know what the difference will be. I understand that if we use int and we divide it, then we can eliminate the rounding number when we do not intend it, but in this case, we should always check that What is divisble before dividing by n 2? So I thought it would be completely safe to use the integer. What am I not seeing?

This is a complete code, copy, paste and run it in. If you want to see yourself, it runs in a few seconds despite it running too much. =)

Your problem is overflow if you enter int n to If you change the long n , you will get the correct answer.

Remember: The number of really big in the sequence is not the limit of the overflow int but in this case (in this case) double s, or long s.

At one point in the series, n is 827,370,449 and you follow the 3n + 1 branch . This value wants to be 2,482,111,348 , but it exceeds the capacity of int (which is 2,147,483,647 in the positive area) and you 1812855 9 48. And things go from there to the south: -)

Then you want to correct your theory with integer (I should say integral ) number is correct. But they have the ability to work.

No comments:

Post a Comment