Thursday, October 24, 2019

C++ Write a code that will print only prime factors.

Code

#include <iostream>
using namespace std;
void prime_factor(int n);

int main()
{
int n;
cout<<"Enter a number then press Enter : ";cin>>n;

prime_factor(n);
return 0;

}

//adding a function to print prime factor
void prime_factor(int n)
{
int exponent,i; // this variable will count the number of times prime factors was running

for( i = 2; i<=n; i++)
// set i = 2 because prime numbers starts at 2
{


exponent = 0; // this variable will count the number of times prime factors was running.
while(n % i == 0)
{
n=n/i; // dividing the value of n and sending back to while loop if it factorable by i again.
exponent++;// adding one to exponent. 
// everytime i gonna transfer a value its gonna keep adding 1 to exponent for that transferred number. 
// if i =2 transferred and n is 20 . the prime factors for 20 //is 2, 2, 5. so for 2 exponent will be count for 2. when the for loop will //transfer for different number it will count for that number.  

if (exponent !=0)
// exponent cant be 0
{
cout<<i<<"^"<<exponent;// print prime factors and exponent. 
if(n!=1)
{
cout<<", ";
}
}

}

}




 OUTPUT - 



C++ BLACKJACK

#include <iostream> #include <ctime> #include <stdlib.h> #include <time.h> #include <string> using namesp...