0

Well here is my code:

#include <stdio.h> 

int main(){
   int n=728,sum = 0, remainder, sump=0, d=2;

   while(n>d){
    if(n%d==0){
        n/=d;
        sump= sump+d;
    }
    else{
        d++;
        }
   }
   sump=sump+d%10+d/10;
   printf("%d\n",sump);

   while(n != 0){
      remainder = n % 10;
      sum = sum + remainder;
      n = n / 10;
   }
   printf("%d\n",sum);
   return 0;
}

Here is what I get when I run the code:

17
4

The problem is that although the sump is correct because the sum of 728 prime factors digits is (2+2+2+7+1+3=17) the sum of digits of 728 is 4 instead of 17 which means that in the second while loop n is equal to 13 which is the last prime factor from the first loop.

What's my mistake and in the second loop n is 13 and not 728?

Please forgive me if my english is bad :S

3
  • 2
    so what is this program supposed to do?
    – user529758
    Jan 26, 2014 at 17:32
  • You didn't store the value of n. try displaying it after the first while loop.
    – AntonH
    Jan 26, 2014 at 17:33
  • Please get the indentation correct.
    – Ed Heal
    Jan 26, 2014 at 17:35

4 Answers 4

2

The value of n is no longer be the 728 after the first while loop. In second while loop you are extracting the digits of n and then trying to add them but those digits are not 7, 2 and 8.
Try this:

int temp = n; 
 ...
while(temp != 0){
     remainder = temp % 10;
     sum = sum + remainder;
     temp = temp / 10;
} 
1

You're clearly modifying n inside your first while loop.

You can reassign 728 to N before the second loop.

1

In the first while loop you are changing the value of n, that's why you are getting a "wrong" value. Either keep a copy of n or refactor your code to use functions.

0
#include <stdio.h> 

int main(){
int n=728,sum = 0, remainder, sump=0, d=2;
int tempn=n;
while(n>d){
if(n%d==0){
    n/=d;
    sump= sump+d;
}
else{
    d++;
    }
 }
sump=sump+d%10+d/10;
printf("%d\n",sump);
n=tempn;
while(n != 0){
  remainder = n % 10;
  sum = sum + remainder;
  n = n / 10;
}
printf("%d\n",sum);
return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.