-
factors
what is wrong with this code, it does not return the desired output.
Code:
#include <stdio.h>
void main() {
int inp, div;
printf("What number do you want the factors of?\n");
scanf("%d", &inp);
for(div=2;div * div < inp; div++) {
if(inp % div == 0)
printf("%d X %d", div, inp / div);
}
printf("\n");
}
-
1) use int main() instead of void main()
2) put a newline in your printf so the printout doesn't run together
3) make 'div * div < inp' into 'div * div <= inp' so that square roots are counted, too.
-
was the void main causing the error, the other stuff wasn't. btw thanx
-
No, #1 wasn't causing the error - void main() is just bad coding practice. #2 made it ugly, and #3 made it not work. (I'm referring to the errors associated with each)
-
It is not the code which is the problem, but the algorithm. When factorising you should search for the smallest factors first and divide the number to factorise by that number. Then check if the result is a prime. If not, then find its smallest factor and divide the result by its smallest factor. Repeat this proces until the result of the division is a prime.
For example, take the number 50. This is not a prime number and its smallest divisor is 2. Now 50 / 2 = 25. Also 25 is not a prime number, its smallest divisor is 5. Now 25 / 5 = 5. Number 5 is a prime number, so the factorisation is: 50 = 2 x 5 x 5.
Code:
#include <stdio.h>
int main()
{
int inp, div;
printf("What number do you want the factors of?\n");
scanf("%d", &inp);
while (div != -1)
{
div = find_smallest_divisor (inp);
if (div == -1)
{
/* No smallest divisor found, so current value of
inp is a prime number and therefore it is the last
factor. */
printf ("%d\n", inp);
}
else
{
/* Smallest divisor found, so current value of inp is not
a prime number and can be divised by div. */
printf ("%d X ", div);
inp /= div;
}
}
return 0;
}
int find_smallest_divisor (int i)
{
/* Find the smallest divisor of a value i. */
int j;
int r = -1;
for (j = 2; j < i && r == -1; j++)
{
if (i % j == 0)
{
r = j;
}
}
return r;
}
-
Code:
#include <iostream.h>
#include <conIO.h>
int main(void)
{
clrscr();
unsigned int num;
cout<<"Enter number to find primes of:";
cin>>num;
for(int c=1;c<=num;c++)
{
if(num%c==0)
cout<<" "<<c;
}
getch();
return 0;
}
This may not be good programming techniques but it works and dos can handle
-
>This may not be good programming techniques
I agree, seeing as how you're using C++.
>but it works
Not if you compile it as C.
>and dos can handle
DOS is not the only operating system around, and certainly not the most popular. A program like this can easily be made portable.