In: Computer Science
Jojo just graduated and moved up to grade 4. Today is his first day in 4th grade. Unfortunately, the lessons are held online because of pandemic. So that the quality of learning remains good, Jojo’s teacher gives a hard task for 4th grader.
The first task is to find the prime factorization of a number. Prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. Prime factorization of a number is breaking a number down into the set of prime numbers which multiply together to result in the original number. Example below is the prime factorization of 1176.
. As a good friend of Jojo, help Jojo to solve the prime factorization task given by his teacher. Format Input There are T testcases. Each testcase contains an integer N which indicates the number to be factorized into prime factorization. Format Output Output T line with format “Case # X: ”, where X indicates the testcase number and then followed by the number prime factorization in ascending order of prime factors with the correct format.As a good friend of Jojo, help Jojo to solve the prime factorization task given by his teacher. Format Input There are T testcases. Each testcase contains an integer N which indicates the number to be factorized into prime factorization. Format Output Output T line with format “Case # X: ”, where X indicates the testcase number and then followed by the number prime factorization in ascending order of prime factors with the correct format.
So I am using C language to solve this problem. Since you have not mentioned which one to use.
The program is as follows:
#include<stdio.h>
#include<math.h>
void primeFactors(int n)
{
while(n%2==0)
{
printf("%d ", 2);
n=n/2;
}
for(int i = 3; i <= sqrt(n); i=i+2)
{
while(n%i==0)
{
printf("%d ", i);
n=n/i;
}
}
if(n>2)
{
printf("%d", n);
}
}
int main()
{
int n;
printf("Enter the Test Case : ");
scanf("%d", &n);
printf("Case 1: ");
primeFactors(n);
return 0;
}
Explanation for the above program:
First of all we have declared a function primeFactors(int n)
In this function we are going to write the logic of our problem statement
The logic is as follows:
1. We have to print the number of 2's that divide our number
- For this we have used while loop
2. We have to check whether the number divides by the prime numbers greater than 2
- For this we have used for loop, initially we say i is 3 and then we increament i by 2 until i is less than square root of our number
3. Again we use while loop so that as many times our number will divide by i that we will print
4. Now we divide our number by i and if our number is greater than 2 we print it
So, this was the logic
now we come to main function
take input as our test case
and print the result for our case