Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C Exercises: Find the last non-zero digit of the factorial of a given positive integer

C Basic Declarations and Expressions: Exercise-92 with Solution

Write a C program to find the last non-zero digit of the factorial of a given positive integer.
For example for 5!, the output will be "2" because 5! = 120, and 2 is the last nonzero digit of 120

Sample Solution:

C Code:

#include <stdio.h>
#include <string.h>

const char ftr[] = {1,1,2,6,4,4,4,8,4,6};

void comp(char i[],int* len)
{
int j;
char c,tmp;
if(i[0] < 5)
    {
        c = i[0];
        (*len)--;
for(j = 0; j < *len; j++)
        {
tmp = (c*10+i[j+1])%5;
i[j] = (c*10+i[j+1])/5;
            c = tmp;
        }
    }
else
    {
        c = 0;
for(j = 0; j < *len; j++)
        {
tmp = (c*10+i[j])%5;
i[j] = (c*10+i[j])/5;
            c = tmp;
        }
    }
}

char fact(char i[],int len)
{
char ans,c,d;
if(len == 1 && i[0] < 5)
return ftr[(int)i[0]];
else
    {
ans = ftr[(int)i[len-1]]*6%10;
comp(i, &len);
        d = (i[len-1] + ((len>1)?i[len-2]*10:0)) & 0x03;
for(c = 0; c < d; c++)
        {
if(ans == 2 || ans == 6)
ans += 10;
ans /= 2;
        }
return fact(i, len) * ans % 10;
    }
}

int main(void)
{
char chr[1002];
int len,i;
char c;
	printf("Input a positive number:\n");
scanf("%s",chr);
len = strlen(chr);
for(i = 0; i<len; i++)
chr[i] -= '0';
        c = fact(chr,len);
printf("The last non-zero digit of the said factorial:\n");
		putchar(c+'0');

putchar(10);
return 0;
}

Sample Output:

Input a positive number:
The last non-zero digit of the said factorial:
0

Flowchart:

C Programming Flowchart: Find  the last non-zero digit of the factorial of a given positive integer.

C programming Code Editor:

Contribute your code and comments through Disqus.

Previous:Write a C program to find the angle between (12:00 to 11:59) the hour hand and the minute hand of a clock.
Next: Write a C program to check if a given number is nearly prime or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



C Programming: Tips of the Day

Static variable inside of a function in C

The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().

The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.

The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().

Ref : https://bit.ly/3fOq7XP