prime factorisation of a number in c++
Sure! Here is an example of how you can perform prime factorization of a number in C++:
#include <iostream>
void primeFactorization(int n) {
while (n % 2 == 0) {
std::cout << 2 << " ";
n = n / 2;
}
for (int i = 3; i * i <= n; i = i + 2) {
while (n % i == 0) {
std::cout << i << " ";
n = n / i;
}
}
if (n > 2)
std::cout << n << " ";
}
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
std::cout << "Prime factors of " << num << " are: ";
primeFactorization(num);
return 0;
}
This program takes a number as input and finds its prime factors. Let's go through the steps in the code:
We include the necessary header file
iostream
to use input/output operations in C++.We define a function
primeFactorization
that takes an integern
as a parameter. This function will perform the prime factorization ofn
and print the prime factors.Inside the
primeFactorization
function, we start by checking if the number is divisible by 2. If it is, we repeatedly divide it by 2 and print 2 as a prime factor until it is no longer divisible by 2.After the above step, we start a loop from 3 to the square root of
n
and increment by 2 in each iteration (to skip even numbers). We check ifn
is divisible byi
. If it is, we repeatedly dividen
byi
and printi
as a prime factor until it is no longer divisible byi
.Finally, if
n
is greater than 2, it means thatn
itself is a prime number. So we printn
as a prime factor.In the
main
function, we ask the user to enter a number.We call the
primeFactorization
function, passing the user input as the argument.The prime factors of the entered number are printed on the console.
The program ends by returning 0.
I hope this helps! Let me know if you have any further questions.