Find Missing Number: Write a PHP function to find the missing number in an array of consecutive integers.

<?php

function findMissingNumber($arr) {
    // Calculate the expected sum of consecutive integers
    $n = count($arr) + 1; // Including the missing number
    $expectedSum = ($n * ($n + 1)) / 2;

    // Calculate the actual sum of the given array
    $actualSum = array_sum($arr);

    // The missing number is the difference between expected sum and actual sum
    $missingNumber = $expectedSum - $actualSum;

    return $missingNumber;
}

// Example usage
$arr = [1, 2, 3, 5, 6, 7, 8];
echo "The missing number is: " . findMissingNumber($arr); // Output: The missing number is: 4

?>

Here’s a step-by-step guide on how to run the PHP script provided:

  • Save it with a .php extension. For example, you can name it find_missing_number.php.
  • Open the PHP File in a Text Editor: Use a text editor like Notepad, Sublime Text, or Visual Studio Code to open the find_missing_number.php file.
  • Write or Copy and Paste the PHP Code: Copy the complete PHP code provided earlier in this conversation and paste it into the find_missing_number.php file.
  • Save the PHP File: After pasting the code, save the find_missing_number.php file.
  • Access the PHP Script: Open your web browser and type the following URL:
http://localhost/your_script_name.php

Replace your_script_name.php with the name of your PHP script file.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Artificial Intelligence