How to use Recursive Function for Large Numbers In PHP
In this approach we use recursive function to handle larger numbers by breaking them down into smaller parts, such as hundreds, thousands, or millions, and recursively converting each part into words.
Example: Below is the implementation of the above approach to convert a given number to words
<?php
function numToWordsRec($number) {
$words = array(
0 => 'zero', 1 => 'one', 2 => 'two',
3 => 'three', 4 => 'four', 5 => 'five',
6 => 'six', 7 => 'seven', 8 => 'eight',
9 => 'nine', 10 => 'ten', 11 => 'eleven',
12 => 'twelve', 13 => 'thirteen',
14 => 'fourteen', 15 => 'fifteen',
16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen',
19 => 'nineteen', 20 => 'twenty', 30 => 'thirty',
40 => 'forty', 50 => 'fifty', 60 => 'sixty',
70 => 'seventy', 80 => 'eighty',
90 => 'ninety'
);
if ($number < 20) {
return $words[$number];
}
if ($number < 100) {
return $words[10 * floor($number / 10)] .
' ' . $words[$number % 10];
}
if ($number < 1000) {
return $words[floor($number / 100)] . ' hundred '
. numToWordsRec($number % 100);
}
if ($number < 1000000) {
return numToWordsRec(floor($number / 1000)) .
' thousand ' . numToWordsRec($number % 1000);
}
return numToWordsRec(floor($number / 1000000)) .
' million ' . numToWordsRec($number % 1000000);
}
// Example usage:
$number = 1234567;
echo "Number $number in words: "
. numToWordsRec($number);
?>
Output
Number 1234567 in words: one million two hundred thirty four thousand five hundred sixty seven
Time Complexity: O(Log N)
Auxiliary Space: O(Log N)
PHP Program to Convert a Given Number to Words
Given an integer N, the task is to convert the given number into words using PHP.
Examples:
Input: N = 438237764
Output: Four Hundred Thirty Eight Million Two Hundred Thirty Seven Thousand Seven Hundred Sixty Four
Input: N = 1000
Output: One Thousand
Below are the approaches to convert a given number to words:
Table of Content
- Using a Pre-defined Array of Words
- Using Recursive Function for Large Numbers