Python非字符串转换式整数文件写入方法及千万位2的平方根写入溢出问题咨询
Got it, let's break down your problems and fix them one by one, plus address your question about writing the integer without converting it to a string.
First, let's understand the errors:
TypeError: write() argument must be str, not int: This is straightforward—Python's filewrite()method only accepts strings or bytes, not integers. You need to convert your number to a string, but...OverflowErrorwhen converting to string: A 10-million-digit integer is massive. Converting it to a string all at once tries to load the entire 10M+ character string into memory, which can exceed your system's memory limits and trigger the overflow.
Solution 1: Write the large integer in chunks (avoids overflow)
Instead of converting the entire integer to a string at once, we'll extract chunks of digits, convert each chunk to a string, and build the final output incrementally. This keeps memory usage low and avoids the overflow. Here's how to modify your code:
import os os.chdir('/home/username/Desktop') def sqroot(a, digits): a = a * (10**(2*digits)) x_prev = 0 x_next = 1 * (10**digits) while x_prev != x_next: x_prev = x_next x_next = (x_prev + (a // x_prev)) >> 1 return x_next def write_large_sqrt_to_file(num, digit_count, filename): chunks = [] chunk_size = 1000 # Adjust based on your memory (smaller = less memory used) temp_num = num # Extract digits from the end (lowest place values) while temp_num > 0: # Grab the last `chunk_size` digits chunk = temp_num % (10 ** chunk_size) # Convert to string and pad with leading zeros to keep chunk length consistent chunk_str = str(chunk).zfill(chunk_size) chunks.append(chunk_str) # Remove the processed digits from the number temp_num = temp_num // (10 ** chunk_size) # Reverse the chunks to get the correct high-to-low digit order full_digit_str = ''.join(reversed(chunks)) # Insert the decimal point: since our number is sqrt(2)*10^digit_count, the decimal goes after the first digit formatted_sqrt = full_digit_str[0] + '.' + full_digit_str[1:] # Use a with-statement to handle file operations safely (auto-closes the file) with open(filename, 'w') as f: f.write(formatted_sqrt) # Calculate sqrt(2) to 10 million digits sqrt2 = sqroot(2, 10000000) # Write to file write_large_sqrt_to_file(sqrt2, 10000000, "Root_2")
Solution 2: Can you write the integer without converting it to a string?
Short answer: No, not if you want human-readable decimal digits.
Integers are stored in binary in memory. If you wrote the raw binary data to a file, it would be unreadable as decimal numbers (it would look like garbage). The only way to get the decimal digits you need is to convert the integer to a string—but by doing it in chunks (as above), you avoid the overflow issue.
Extra Tips
- Adjust
chunk_size: If you still hit memory issues, lower the chunk size (e.g., 500). If you have plenty of memory, increase it (e.g., 10000) to speed up the process. - Verify your output: Check the first few digits to ensure correctness—sqrt(2) starts with
1.41421356237309504880... - Use
withstatements for files: This ensures the file gets closed even if an error occurs, which is safer than manualclose()calls.
内容的提问来源于stack exchange,提问作者RandomCoder

