August 15th, 2013, 03:18 PM

Help with prime divisors of a number
Hello
I've built a program that has 2 functions. Prime_num simply checks if a number is prime or not, while divisor checks if the number is divisible by some random number
But now i have to show all the prime divisors of the number and I have no idea how to do it
Here is the code:
#include<stdio.h>
int prime_num(int num);
int divisor(int a, int b);
int main(){
int n,x;
printf("Type any number: \n");
scanf("%d",&n);
printf("%d\n",primo(n));
printf("Type a divisor: \n");
scanf("%d",&x);
printf("%d",divisor(n,x));
}
int prime_num(int num){
int i;
for(i=2; i<num; i++){
if(num%i==0 && i!=num)
return 0;
}
return 1;
}
int divisor(int a, int b){
if((a%b)==0){
return 1;
}
return 0;
}
Any tips?
August 15th, 2013, 03:54 PM

You know that prime divisors will all need to be prime numbers, right?
So create a list of prime numbers, and work through them testing whether the number is evenly divisible by that number.
If it is, then divide the number and the quotient will be the new number to be tested.
Start with the new number using the current prime (since you know that none of the lower primes are a factor or else they would have tested positive already) and continue.
When the quotient becomes one, you should be done.
August 15th, 2013, 05:39 PM

Thanks
Originally Posted by dwise1_aol
You know that prime divisors will all need to be prime numbers, right?
So create a list of prime numbers, and work through them testing whether the number is evenly divisible by that number.
If it is, then divide the number and the quotient will be the new number to be tested.
Start with the new number using the current prime (since you know that none of the lower primes are a factor or else they would have tested positive already) and continue.
When the quotient becomes one, you should be done.
Thank you so much
It took me a while, but I managed to do it with a for loop, dividing the number by an array with the prime numbers :D
August 15th, 2013, 07:59 PM

Originally Posted by oliver_sachs
Thank you so much
It took me a while, but I managed to do it with a for loop, dividing the number by an array with the prime numbers :D
Judging from what you said, here's another way you could have solved your problem. If you have some free time, you might want to compare this to your solution. It's always interesting to understand different ways of solving problems, and it could help you out later on.
Code:
int main(void) {
int number = 12365322;
int factor = 2;
while (number != 1) {
if (number % factor == 0) {
number /= factor;
printf("%d ", factor);
}
else {
factor++;
}
}
return 0;
}
Comments on this post