Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

An integer p lis said to be prime if p is divisible only by 1 and by p itself (s

ID: 3790920 • Letter: A

Question

An integer p lis said to be prime if p is divisible only by 1 and by p itself (strictly speaking, a prime p is divisible by t1 and tp, but this is not relevant for the problem at hand). Every integer n 1 can be written in a unique way as a product of primes in nondecreasing order. The nondecreasing sequence of primes in this product is called the prime factorization of n. Here are a few examples: Since 6 2.3, the prime factorization of 6 is 2, 3. Since 12 2.2.3, the prime factorization of 12 is 2, 2, 3. The prime factorization of 7 is 7. The prime factorization of 300300 is 2,2, 3,5, 5, 7, 11,13. Write a C program, called prime-factorization. c, that prompts the user to enter an integer and then prints its prime factorization. The program program should keep doing this repeatedly as long as the user enters an integer greater than 1. If the user enters an integer less than or equal to 1, the program should simply terminate. If the user enters a non-integer, the program should terminate with an appropriate error message. Here is one sample run of such a program, assuming that the executable file is called prime-factorization.

Explanation / Answer

// Program to print all prime factors
# include <stdio.h>
# include <math.h>

// A function to print all prime factors of a given number n
void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n%2 == 0)
{
printf("%d ", 2);
n = n/2;
}

// n must be odd at this point. So we can skip one element (Note i = i +2)
for (int i = 3; i <= sqrt(n); i = i+2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
printf("%d ", i);
n = n/i;
}
}

// This condition is to handle the case whien n is a prime number
// greater than 2
if (n > 2)
printf ("%d ", n);
}

/* Driver program to test above function */
int main()
{
while(1)
{
printf (" Enter an Integer :");
int n;
scanf("%d",&n);

primeFactors(n);
}

return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote