program to find the prime factors of a number

Problem statement:- Program to find the prime factors of a number.

Sample Input/Output:-

Sample Input First: 45                         Sample Output First: 3 3 5

Sample Input Second: 30                    Sample Output Second2 3 5

Explanation:- 

For output 1st: 3*3*5=45

For output 2nd: 2*3*5=30

Data requirement:-

   Input Data:- num

  Output Data:-i, num


Program in C
  
Here is the source code of the C Program to find the prime factors of a number.

Code:

#include<stdio.h>
#include<math.h>
int main()
{
    int num,i;
    printf("Enter a number:");
    scanf("%d",&num);
    printf("Prime Factors of %d are\n",num);
    while(num%2==0)
    {
        printf("2 ");
        num=num/2;
    }
    for(i=3;i<=sqrt(num);i=i+2)
    {
        while(num%i==0)
        {
            printf("%d ",i);
            num=num/i;
        }
    }
   if(num>2)
     printf("%d ",num);
}

Input/Output:
Enter a number:45
Prime Factors of 45 are
3 3 5

Program in C++
  
Here is the source code of the C++ Program to find the prime factors of a number.

Code:

#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    int num;
    cout<<"Enter a number:";
    cin>>num;
    cout<<"Prime Factors of "<<num<<" are\n";
    while(num%2==0)
    {
        cout<<2<<" ";
        num=num/2;
    }
    for(int i=3;i<=sqrt(num);i=i+2)
    {
        while(num%i==0)
        {
            cout<<i<<" ";
            num=num/i;
        }
    }
   if(num>2)
     cout<<num<<" ";
}

Input/Output:
Enter a number:30
Prime Factors of 30 are
2 3 5

Program in Java
  
Here is the source code of the Java Program to find the prime factors of a number.

Code:

import java.util.Scanner;
public class PrimeFactors {

public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
int num,i;
    System.out.println("Enter a number:");
    num=cs.nextInt();
    System.out.println("Prime Factors of "+num+" are");
    while(num%2==0)
    {
        System.out.print("2 ");
        num=num/2;
    }
    for(i=3;i<=Math.sqrt(num);i=i+2)
    {
        while(num%i==0)
        {
            System.out.print(i+" ");
            num=num/i;
        }
    }
   if(num>2)
     System.out.print(num+" ");
cs.close();
}
}

Input/Output:
Enter a number:
39
Prime Factors of 39 are
3 13 

Program in Python
  
Here is the source code of the Python Program to find the prime factors of a number.

Code:

import math
num=int(input("Enter a number:"))
print("Prime Factors of ",num,end=" are \n")
while num%2==0:
    print(2,)
    num=num/2
for i in range(3,int(math.sqrt(num))+1,2):
   while num%i==0:
      print(i,)
      num = num/i
if num>2:
  print(num)

Input/Output:
Enter a number:25
Prime Factors of  25 are 
5
5

C/C++/Java/Python Practice Question






Post a Comment

0 Comments