Write a program to find the factors of the given number.
Example 1:
Input :24
Output:1 2 3 4 6 8 12 24
Example 2:
Input:13
Output: 1 13
Approach: Simple
Java
import java.util.ArrayList;import java.util.List;public class NumberFactor {public static void main(String[] args) {int num = 24;List<Integer> factor = calculateFactor(num);System.out.println("Factor is " + factor);}private static List<Integer> calculateFactor(int num) {ArrayList<Integer> arr = new ArrayList<>();for (int i = 1; i <= num; i++) {if (num % i == 0)arr.add(i);}return arr;}}// Time Complexity :O(n)
C++
#include <bits/stdc++.h>using namespace std;//function to find factors of//the given numbervector<int> factorOfNumber(int num){vector<int> factor;for(int i=1;i<=num;i++){//num%i==0 then i is a factor of numif(num%i==0)factor.push_back(i);}return factor;}int main(){int num=24;vector<int> factor=factorOfNumber(num);for(int i=0;i<factor.size();i++)cout<<factor[i]<<" ";return 0;}//Time complexity: O(n)
Approach: Efficient
Java
import java.util.ArrayList;import java.util.List;public class NumberFactor {public static void main(String[] args) {int num = 24;List<Integer> factor = calculateFactor(num);System.out.println("Factor is " + factor);}private static ArrayList<Integer> calculateFactor(int num) {ArrayList<Integer> arr = new ArrayList<>();for (int i = 1; i * i <= num; i++) {if (num % i == 0) {if (num / i == i) {arr.add(i);} else {arr.add(i);arr.add(num / i);}}}return arr;}// Time Complexity : O(sqrt(n))
C++
#include <bits/stdc++.h>using namespace std;//function to find factors of//the given numbervector<int> factorOfNumber(int num){vector<int> factor;for(int i=1;i*i<=num;i++){//num%i==0 then i is a factor of numif(num%i==0){//if num/i and i both are sameif(num/i==i)factor.push_back(i);//if num/i and i both are differentelse{factor.push_back(i);factor.push_back(num/i);}}}return factor;}int main(){int num=24;vector<int> factor=factorOfNumber(num);for(int i=0;i<factor.size();i++)cout<<factor[i]<<" ";return 0;}//Time complexity: O(sqrt(n))
No comments:
Post a Comment