Reputation: 51
I am making a program to find prime factorials of a given number.
Although the program works fine, I have two problems.
1. when i enter an odd number, it prints 2 in the result although 2 should not be in it.
2. After 15 seconds , it turns into an infinite loop , Which is really creepy.
#include<stdio.h>
#include<conio.h>
int num(int); // Making a function for finding prime factors
int main()
{
int i,j;
printf("Enter any number");
scanf("%d",&i);
num(i);
getch();
}
int num(int i)
{
int a=2;
while(a<=i)
{
if(i%a==0) //if the number is divisible then divide it
i=i/a;
printf(" %d",a);
if(i%a!=0)
{
i%a;
while(i%a!=0)// If it is not divisible by 2 then increment it until it is
a++;
}
}
}
Upvotes: 1
Views: 130
Reputation: 8602
It always prints 2 because the print statement is not part of the if which tests for mod 0. It goes into an infinite loop because once a passes i, the second while loop will never exit.
Upvotes: 4
Reputation: 15397
The infinite loop is your second while
loop, while(i%a!=0)
. For a prime number, this will continue endlessly. There are smart ways to fix that, but at the very least, change it to
while(i%a!=0 && a<=i)
I'm not sure why 2 is coming up on odd numbers, still thinking that part through.
EDIT As Fred mentioned, the printout is not part of the if statement, causing 2 to always show up. Personally, I recommend getting into the habit of always putting { }
after an if
statement. Even if you've been coding for decades, this will make sure you get the right statements in your condition.
Upvotes: 2