PHP阿姆斯特朗数程序报错:Maximum execution time of 30 seconds exceeded求助
Fixing "Maximum execution time exceeded" for Armstrong Number Program in PHP
Hey Veronica, great job diving into PHP and tackling Armstrong numbers—let's get that timeout issue sorted out! The error you're seeing happens because your original code is probably doing a lot of unnecessary work, making it too slow to finish within PHP's default 30-second limit. Let's break down the fixes step by step.
Why the Timeout Happens
Most beginner implementations fall into these traps:
- Repeating calculations: Recalculating the number of digits for the same number multiple times
- No early termination: Continuing to sum digits even when the total already exceeds the original number
- Inefficient digit splitting: Using slow methods to pull apart each number's digits
Optimized Solution Code
Here's a fast, efficient version that will run well within the time limit:
<?php // Optional: Only if you still hit timeout after optimizing (not recommended first) // set_time_limit(60); for ($num = 0; $num <= 10000; $num++) { // Calculate digit count ONCE per number $digitCount = strlen((string)$num); $sum = 0; $temp = $num; // Calculate sum of digits raised to the digit count power while ($temp > 0) { $digit = $temp % 10; $sum += pow($digit, $digitCount); // Early exit: Stop calculating if sum already exceeds the number if ($sum > $num) { break; } $temp = (int)($temp / 10); } // Check if it's an Armstrong number and format output if ($sum === $num) { $digits = str_split((string)$num); $expressionParts = []; foreach ($digits as $d) { $expressionParts[] = "$d^$digitCount"; } $expression = implode(" + ", $expressionParts); echo "$num ist eine Armstrong-Zahl: $expression = $num\n"; } } ?>
Key Optimizations Explained
- Single digit count calculation: We convert the number to a string once to get its length (digit count) instead of recalculating it every time we process a digit.
- Early termination: If at any point the sum of the powered digits exceeds the original number, we break out of the loop immediately—no need to waste cycles on the remaining digits.
- Efficient digit extraction: Using modulo (
%) and integer division (/) is a fast way to pull digits from a number without string manipulation overhead (though string methods work too, this is slightly faster).
Testing the Code
When you run this, it will output exactly the format you need, from 0 up to 9474 (the largest Armstrong number under 10000) without hitting the timeout.
内容的提问来源于stack exchange,提问作者Veronica
相关产品推荐
相关产品推荐

