Write a program in C that does the following: 1.Prompt user for a positive integ
ID: 670045 • Letter: W
Question
Write a program in C that does the following:
1.Prompt user for a positive integer greater than 1 and sanity check the input.
2. Calculate the smallest factor of the number (other than 1).
3. Using some reasonable message, the smallest factor is to be output to the user.
4. Divide the number by the smallest factor to generate a new integer and repeat the process finding the smallest factor of the new number.
5. Repeat until the smallest factor is equal to the number itself.
So far, I have managed to get the program to output the lowest factor but am unable to make it loop so it repeats the process of the new number, etc...
This is the code I have so far...
#include "mbed.h"
DigitalOut myled(LED_GREEN);
Serial pc(USBTX, USBRX);
int main()
{
pc.baud(115200);
int num, temp=0,i, j;
int num2;
pc.printf("Enter a positive number greater than 1. ");
pc.scanf("%d",&num);
if(num <= 1)
{
pc.printf("Invalid entry, please enter a positive number greater than 1. ");
pc.scanf("%d",&num);
}
while(temp != num)
{
for(i=2; i<=num/2; i++)
{
if(num%i==0)
{
temp=i;
break;
}
}
pc.printf("The smallest factor is %d " , temp);
return 0;
}
}
Explanation / Answer
#include "mbed.h"
DigitalOut myled(LED_GREEN);
Serial pc(USBTX, USBRX);
int main()
{
pc.baud(115200);
int num, temp=0,i, j;
int num2;
pc.printf("Enter a positive number greater than 1. ");
pc.scanf("%d",&num);
if(num <= 1)
{
pc.printf("Invalid entry, please enter a positive number greater than 1. ");
pc.scanf("%d",&num);
}
temp = num;
while(temp != 1)
{
for(i=2; i<=num/2; i++)
{
if(num%i==0)
{
break;
}
}
pc.printf("The smallest factor is %d " , i);
temp = temp/i;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.