Multiplying the digits of an integer and continuing the process gives the surprising result that the sequence of products always arrives at a single digit number. For example,

715 ---- 35 ---- 15 ---- 5

27 ---- 14 ---- 4

4000 ---- 0


The number of times products need to be calculated to reach a single digit is called the persistence number of that integer. Thus, the persistence number of 715 is 3, the persistence number of 27 is 2, the persistence number of 4000 is 1, and the persistence number of 9 is 0.

You are to write a program that will continually prompt the user to enter a positive integer until EOF has been entered via the keyboard. For each number entered your program should output the persistence of the number.

i thought my code would work, but it always says the persistence is 1
any help?

#include <stdio.h>

int persistence(int x);
int main(int argc, char *argv[]){
  int x;

  printf("Insert an integer: ");
  scanf("%d", &x);

  printf("\nThe persistence of %d is %d.\n", x, persistence(x));


int persistence(int x){
  int digit, y = 1, pers = 0;

  while( x > 9 ){
          digit = x % 10;
          y = y * digit;
          x = x / 10;
   }while( x > 9 );

    x = y;

  return( pers );

You need to set y to 1 at the top of the loop so it's initialized every iteration. Your do{}while() condition should be x > 0 since you want to multiply every digit together here. The outer while() condition should still be x > 9.

This article has been dead for over six months. Start a new discussion instead.