![]() |
Given a Number, the task is to find all factors of the number in PHP. Factors are numbers that divide another number without leaving a remainder. In this article, we will cover all approaches to find all factors of a number using PHP. Table of Content Approach 1: All Factors of a Number using a LoopThe simple method is to iterate through all numbers from 1 to N and check if each number divides the given number evenly.
Output Factors: 1, 2, 3, 4, 6, 12 First, we start from 1 and iterate till the given number N. For each iteration, we check if the current number divides the given number evenly (i.e., the remainder is 0). If it does, we add it to the list of factors. Approach 2: All Factors of a Number using Square Root OptimizationSince factors come in pairs (except for perfect squares), we only need to iterate up to the square root of the given number.
Output Factors: 1, 2, 3, 4, 6, 12 In this approach, we iterate up to the square root of the given number. For each factor we find, we also add its pair (the result of dividing the number by the factor) to the list of factors. Approach 3: All Factors of a Number using RecursionWe can also use recursion to find all factors. In recursion, we call the same function again and again to find all factors of number.
Output Factors: 1, 2, 3, 4, 6, 12 In this approach, the function calls itself recursively, incrementing the divisor until it reaches the square root of the given number. |
Reffered: https://www.geeksforgeeks.org
PHP |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 21 |