I am trying to find numbers between 1 and 100000000 which are both perfect squares and perfect cubes.
I have written the code successfully and the results are good. The problem is coming with printf.
When I print the results seperately, they're right.. when I print them in the same line, it is showing 0....
please check the code below:
#include <stdio.h>
void sqroot(long long int number, long long int *prevsqroot, long long int *sqexists)
{
long long int i;
*sqexists = 0;
for(i= *prevsqroot; i<=number; i++)
{
long long int var = i*i;
if (var == number)
{
*prevsqroot = i;
*sqexists = 1;
break;
}
if (var > number)
{
break;
}
}
}
void curoot(long long int number, long long int prevsqroot, long long int *prevcuroot, long long int *cuexists)
{
long long int i;
*cuexists = 0;
for(i=*prevcuroot; i<=prevsqroot; i++)
{
long long int var = i*i*i;
if (var == number)
{
*prevcuroot = i;
*cuexists = 1;
break;
}
if (var > number)
{
break;
}
}
}
main()
{
long long int i;
long long int prevsqroot = 1;
long long int prevcuroot = 1;
long long int sqexists=0, cuexists=0;
for (i=1; i<=1000000000; i++)
{
sqroot(i, &prevsqroot, &sqexists);
if (sqexists ==1)
{
curoot(i, prevsqroot, &prevcuroot, &cuexists);
if (cuexists ==1)
{
printf("Squareroot is %6d\n", prevsqroot);
printf("Cuberoot is %6d\n", prevcuroot);
printf("Number is %9d Sqroot is %6d Curoot is %6d\n", i, prevsqroot, prevcuroot);
}
}
}
printf("Successful!\n");
getchar();
}
notice that there are three printfs under the if above... the first
two printfs are working fine... but when i do the same thing in the thrid printf, it is not working..
another problem is that when i run this code in TC++, I get one extra problem, it is showing i as a negative number ... however, the squareroots and cuberoots calculated are right ...
Can anyone tell me what's gone wrong with this ?