Write a Code in C++ : An integer is said to be prime if it is divisible by 1 and
ID: 3563497 • Letter: W
Question
Write a Code in C++ :
An integer is said to be prime if it is divisible by 1 and itself. Forexample, 2, 3 and 5 are prime but 4, 6 and 8 are not ( We note that 1 is not considered to be a prime number). Every integer may be written as the product of prime numbers, for example:
4 = 2*2 , 6 = 2*3, 12 = 2*2*3, 11 = 11,
25 = 5*5, 26 = 2*13 17 = 17, 38 = 2*19
This is known as prime factorization. Write a program that will receive an integer number and it will output its prime factorization. For example:
12 = 2^2 ? 3, 100 = 2^2 ? 5^2
Note: Each divisor of a number can be itself expressed as a product of prime
numbers.
Explanation / Answer
=====================================
Program
=====================================
#include<iostream.h>
void primeFactors(int n);
int main()
{
int n;
cout<<"Enter a number n ";
cin>>n;
cout<<"Prime Factors for the "<<n<<" is ";
primeFactors(n);
return 0;
}
void primeFactors(int n)
{
while (n%2 == 0)
{
cout<<2<<" ";
n = n/2;
}
for (int i = 3; i <= sqrt(n); i = i+2)
{
while (n%i == 0)
{
cout<<i<<" ";
n = n/i;
}
}
if (n > 2)
cout<<n<<" ";
}
====================================
Output
====================================
Case1:
Enter a number n
10
Prime Factors for the 10 is
2 5
Case2:
Enter a number n
12
Prime Factors for the 12 is
2 2 3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.