Rumah > Artikel > pembangunan bahagian belakang > Operasi Tolak Perdana
2601. Operasi Tolak Perdana
Kesukaran: Sederhana
Topik: Tatasusunan, Matematik, Carian Binari, Tamak, Teori Nombor
Anda diberi 0-diindeks nombor tatasusunan integer dengan panjang n.
Anda boleh melakukan operasi berikut seberapa banyak kali yang anda mahu:
Kembali benar jika anda boleh menjadikan nombor tatasusunan yang semakin meningkat menggunakan operasi di atas dan palsu sebaliknya.
A tatasusunan yang semakin meningkat ialah tatasusunan yang setiap elemennya lebih besar daripada elemen sebelumnya.
Contoh 1:
Contoh 2:
Contoh 3:
Kekangan:
Petunjuk:
Penyelesaian:
Kita perlu memecahkan algoritma dan menyesuaikannya dengan sintaks dan fungsi PHP. Penyelesaian terutamanya melibatkan langkah-langkah berikut:
Let's implement this solution in PHP: 2601. Prime Subtraction Operation
primeSubOperation([4, 9, 6, 10]) ? 'true' : 'false'; // Output: true echo $solution->primeSubOperation([6, 8, 11, 12]) ? 'true' : 'false'; // Output: true echo $solution->primeSubOperation([5, 8, 3]) ? 'true' : 'false'; // Output: false ?>Explanation:
primeSubOperation: Loops through each element in nums and checks if we can make each element greater than the previous one by subtracting an appropriate prime.
- We use $this->findLargestPrimeLessThan to find the largest prime less than num - prevNum.
- If such a prime exists, we subtract it from the current num.
- If after subtracting the prime, the current num is not greater than prevNum, we return false.
- Otherwise, we update prevNum to the current num.
sieveEratosthenes: Generates all primes up to 1000 using the Sieve of Eratosthenes and returns them as an array.
findLargestPrimeLessThan: Uses binary search to find the largest prime less than a given limit, ensuring we find the optimal prime for subtraction.
Complexity Analysis
This solution will return true or false based on whether it is possible to make nums strictly increasing by performing the described prime subtraction operations.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
Atas ialah kandungan terperinci Operasi Tolak Perdana. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!