Ticker

6/recent/ticker-posts

Factors Finding with Solution




Factors Finding:

Problem Description:

You are given a number N and find all the distinct factors of N.

Input:

·       First-line will contain the number N.

Output:

·       In the first line print number of distinct factors of N.

·       In the second line print all distinct factors in ascending order separated by space.

Constraints

·       1≤N≤106

Sample Input 1:

            4

Sample Output 1:

            3

            1 2 4

Sample Input 2:

            6

Sample Output 2:

            4

            1 2 3 6

EXPLANATION:

·       In the first example, all factors of 4 are 1, 2, 4.

·       In the second example, all factors of 6 are 1, 2, 3, 6.


Solution:

C++:

#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    int k = 0;
    int primeNo[n];
    for (int i = 1; i <= n; i++)
    {
        if (n % i == 0)
        {
            primeNo[k] = i;
            k++;
        }
    }
    cout << k << endl;
    for (int i = 0; i < k; i++)
    {
        cout << primeNo[i] << " ";
    }

    return 0;
}



JAVA:

import java.util.*;
import java.lang.*;
import java.io.*;

class CompetitiveCoding {
    public static void main(String[] argsthrows java.lang.Exception {
        LinkedList<IntegerprimeNo = new LinkedList<Integer>();
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int k = 0;
        for (int i = 1; i <= n; i++) {
            if (n % i == 0) {
                k++;
                primeNo.add(i);
            }
        }
        Iterator<Integerit = primeNo.iterator();
        System.out.println(k);
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
    }
}


Don't forget to subscribe and share this post.

Post a Comment

0 Comments