7) Factor an input integer into it\'s prime numbers. Create a structure to hold
ID: 3603247 • Letter: 7
Question
7) Factor an input integer into it's prime numbers. Create a
structure to hold the array of prime numbers. Any number between
[2,10000] where n is not a prime > 100 will be a valid number to
check for prime factors.
struct Prime{
unsigned char prime;
unsigned char power;
};
struct Primes{
Prime *prime;
unsigned char nPrimes;
};
Output the number and it's primes -> 120 = 2^3*3^1*5^1
So create a function
Primes *factor(int);-> Input an integer, return all prime factors
void prntPrm(Primes *); -> Output all prime factors
Explanation / Answer
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 when n
// is a prime number greater than 2
if (n > 2)
printf ("%d ", n);
}
/* Driver program to test above function */
int main()
{
int n = 315;
primeFactors(n);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.