How to check whether a no is factorial or not? - c

I have a problem, then given some input number n, we have to check whether the no is factorial of some other no or not.
INPUT 24, OUTPUT true
INPUT 25, OUTPUT false
I have written the following program for it:-
int factorial(int num1)
{
if(num1 > 1)
{
return num1* factorial(num1-1) ;
}
else
{
return 1 ;
}
}
int is_factorial(int num2)
{
int fact = 0 ;
int i = 0 ;
while(fact < num2)
{
fact = factorial(i) ;
i++ ;
}
if(fact == num2)
{
return 0 ;
}
else
{
return -1;
}
}
Both these functions, seem to work correctly.
When we supply them for large inputs repeatedly, then the is_factorial will be repeatedly calling factorial which will be really a waste of time.
I have also tried maintaining a table for factorials
So, my question, is there some more efficient way to check whether a number is factorial or not?

It is wasteful calculating factorials continuously like that since you're duplicating the work done in x! when you do (x+1)!, (x+2)! and so on.
One approach is to maintain a list of factorials within a given range (such as all 64-bit unsigned factorials) and just compare it with that. Given how fast factorials increase in value, that list won't be very big. In fact, here's a C meta-program that actually generates the function for you:
#include <stdio.h>
int main (void) {
unsigned long long last = 1ULL, current = 2ULL, mult = 2ULL;
size_t szOut;
puts ("int isFactorial (unsigned long long num) {");
puts (" static const unsigned long long arr[] = {");
szOut = printf (" %lluULL,", last);
while (current / mult == last) {
if (szOut > 50)
szOut = printf ("\n ") - 1;
szOut += printf (" %lluULL,", current);
last = current;
current *= ++mult;
}
puts ("\n };");
puts (" static const size_t len = sizeof (arr) / sizeof (*arr);");
puts (" for (size_t idx = 0; idx < len; idx++)");
puts (" if (arr[idx] == num)");
puts (" return 1;");
puts (" return 0;");
puts ("}");
return 0;
}
When you run that, you get the function:
int isFactorial (unsigned long long num) {
static const unsigned long long arr[] = {
1ULL, 2ULL, 6ULL, 24ULL, 120ULL, 720ULL, 5040ULL,
40320ULL, 362880ULL, 3628800ULL, 39916800ULL,
479001600ULL, 6227020800ULL, 87178291200ULL,
1307674368000ULL, 20922789888000ULL, 355687428096000ULL,
6402373705728000ULL, 121645100408832000ULL,
2432902008176640000ULL,
};
static const size_t len = sizeof (arr) / sizeof (*arr);
for (size_t idx = 0; idx < len; idx++)
if (arr[idx] == num)
return 1;
return 0;
}
which is quite short and efficient, even for the 64-bit factorials.
If you're after a purely programmatic method (with no lookup tables), you can use the property that a factorial number is:
1 x 2 x 3 x 4 x ... x (n-1) x n
for some value of n.
Hence you can simply start dividing your test number by 2, then 3 then 4 and so on. One of two things will happen.
First, you may get a non-integral result in which case it wasn't a factorial.
Second, you may end up with 1 from the division, in which case it was a factorial.
Assuming your divisions are integral, the following code would be a good starting point:
int isFactorial (unsigned long long num) {
unsigned long long currDiv = 2ULL;
while (num != 1ULL) {
if ((num % currDiv) != 0)
return 0;
num /= currDiv;
currDiv++;
}
return 1;
}
However, for efficiency, the best option is probably the first one. Move the cost of calculation to the build phase rather than at runtime. This is a standard trick in cases where the cost of calculation is significant compared to a table lookup.
You could even make it even mode efficient by using a binary search of the lookup table but that's possibly not necessary given there are only twenty elements in it.

If the number is a factorial, then its factors are 1..n for some n.
Assuming n is an integer variable, we can do the following :
int findFactNum(int test){
for(int i=1, int sum=1; sum <= test; i++){
sum *= i; //Increment factorial number
if(sum == test)
return i; //Factorial of i
}
return 0; // factorial not found
}
now pass the number 24 to this function block and it should work. This function returns the number whose factorial you just passed.

You can speed up at least half of the cases by making a simple check if the number is odd or even (use %2). No odd number (barring 1) can be the factorial of any other number

#include<stdio.h>
main()
{
float i,a;
scanf("%f",&a);
for(i=2;a>1;i++)
a/=i;
if(a==1)
printf("it is a factorial");
else
printf("not a factorial");
}

You can create an array which contains factorial list:
like in the code below I created an array containing factorials up to 20.
now you just have to input the number and check whether it is there in the array or not..
#include <stdio.h>
int main()
{
int b[19];
int i, j = 0;
int k, l;
/*writing factorials*/
for (i = 0; i <= 19; i++) {
k = i + 1;
b[i] = factorial(k);
}
printf("enter a number\n");
scanf("%d", &l);
for (j = 0; j <= 19; j++) {
if (l == b[j]) {
printf("given number is a factorial of %d\n", j + 1);
}
if (j == 19 && l != b[j]) {
printf("given number is not a factorial number\n");
}
}
}
int factorial(int a)
{
int i;
int facto = 1;
for (i = 1; i <= a; i++) {
facto = facto * i;
}
return facto;
}

public long generateFactorial(int num){
if(num==0 || num==1){
return 1;
} else{
return num*generateFactorial(num-1);
}
}
public int getOriginalNum(long num){
List<Integer> factors=new LinkedList<>(); //This is list of all factors of num
List<Integer> factors2=new LinkedList<>(); //List of all Factorial factors for eg: (1,2,3,4,5) for 120 (=5!)
int origin=1; //number representing the root of Factorial value ( for eg origin=5 if num=120)
for(int i=1;i<=num;i++){
if(num%i==0){
factors.add(i); //it will add all factors of num including 1 and num
}
}
/*
* amoong "factors" we need to find "Factorial factors for eg: (1,2,3,4,5) for 120"
* for that create new list factors2
* */
for (int i=1;i<factors.size();i++) {
if((factors.get(i))-(factors.get(i-1))==1){
/*
* 120 = 5! =5*4*3*2*1*1 (1!=1 and 0!=1 ..hence 2 times 1)
* 720 = 6! =6*5*4*3*2*1*1
* 5040 = 7! = 7*6*5*4*3*2*1*1
* 3628800 = 10! =10*9*8*7*6*5*4*3*2*1*1
* ... and so on
*
* in all cases any 2 succeding factors inf list having diff=1
* for eg: for 5 : (5-4=1)(4-3=1)(3-2=1)(2-1=1)(1-0=1) Hence difference=1 in each case
* */
factors2.add(i); //in such case add factors from 1st list " factors " to " factors2"
} else break;
//else if(this diff>1) it is not factorial number hence break
//Now last element in the list is largest num and ROOT of Factorial
}
for(Integer integer:factors2){
System.out.print(" "+integer);
}
System.out.println();
if(generateFactorial(factors2.get(factors2.size()-1))==num){ //last element is at "factors2.size()-1"
origin=factors2.get(factors2.size()-1);
}
return origin;
/*
* Above logic works only for 5! but not other numbers ??
* */
}

Related

Prime Number between given interval

Given below is the code for finding prime numbers between the interval entered by the user.
#include <stdio.h>
int main() {
int n1, n2, i, flag;
scanf("%d%d", &n1, &n2);
for (i = n1; i <= n2; i++) {
flag = prime(i);
if (flag == 1)
printf("\n%d", i);
}
return 0;
}
int prime(int n) {
int j, flag = 1;
for (j = 2; j <= n / 2; j++) {
if (n % j == 0) {
flag = 0;
break;
}
}
return flag;
}
Can anyone explain me how this code deals with odd number, which are not prime (for ex: 15, 21, 25, etc)
int prime(int n) {
int j, flag = 1;
for (j = 2; j <= n / 2; j++) {
if (n % j == 0) {
flag = 0;
break;
}
}
return flag;
}
See in this prime function, when we observe the iteration of for loop if value of n is 15 then it will look like this:
for (j = 2; j <= 15 / 2; j++)
I agree this is true. Because 2<7.
Since the condition is true we will enter inside the for loop:
if(n%j==0){
flag=0;
break;
}
Now, since n=15 and j=2, value of n%j=1, which is obviously not equals to 0; so if loop will not be executed and the prime function will return flag =1; and the main function will print 15 as a prime.
But, after Executing the program the code is showing the correct results: it's not showing 15 as a prime.
So can anyone please help me understand the logic behind this code? (Actually I want to understand how this code is eliminating non-prime odd numbers.)
You checked the execution for j==2, but since there is a for loop for(j=2;j<=n/2;j++). The code will run from j=2 to j=n/2. So, if you consider all the iterations, you will realize that the function is working fine.
The first if statement is false, so for j==2, the program won't go inside the if statement.
The loop will iterate for the next value of j, which is 3. Since 15%3 == 0, the program will execute the statements within the if statement and return that 15 is not a prime number.
for(j=2;j<=n/2;j++){
if(n%j==0){
flag=0;
break;
}
}
In the case of n=15, the loop starts at i=2, the test i<=n/2 is true because 2<=7, then 15%2 is 1, hence the loop proceeds and i is incremented to 3, the loop test is true again because 3<=7 but 15%3 is 0 so flag is set to 0 and returned.
Note these remarks:
the code does not have a recursive function. You merely call a function prime() to check each number in the interval for primality.
prime() should be defined or at least declared before the main() function that calls it.
you can test the return value of prime(i) directly. No need for a flag variable.
for prime numbers, the loop will iterate way too far: you can change the test to j <= n / j to stop at the square root of n.
you can return directly from the loop body.
you should output the newline after the number.
Here is a modified version:
#include <stdio.h>
int isprime(int n) {
int j;
for (j = 2; j <= n / j; j++) {
if (n % j == 0)
return 0;
}
return 1;
}
int main() {
int n1, n2, i;
if (scanf("%d%d", &n1, &n2) != 2)
return 1;
for (i = n1; i <= n2; i++) {
if (isprime(i))
printf("%d\n", i);
}
return 0;
}
Can anyone explain me how this code deals with odd number, which are not prime (for ex: 15, 21, 25, etc)
int prime(int n) {
int j, flag = 1;
for (j = 2; j <= n / 2; j++) {
if (n % j == 0) {
flag = 0;
break;
}
}
return flag;
}
Well this function doesn't need to handle specially nonprime numbers, based on the fact that if we can divide the number n by something (be prime or not), the number will be compose. What it does it to get out of the loop (with flag changed into 0) as soon as it finds a number j that divides n.
There's an extra optimization, that can save you a lot of time, that consists on calculating numbers until the integer rounded down square root of n as, if you can divide the number by a number that is greater than the square root, for sure there will be a number that is less than the square root that also divides n (the result of dividing the original number by the first will give you a number that is lower than the square root) so you only need to go up until the square root. While calculating the square root can be tedious (there's a library function, but let's go on), it is only done once, so it is a good point to use it. Also, you can initialy try dividing the number by two, and then skip all the even numbers, by adding 2 to j, instead of incrementing.
#include <math.h>
/* ... */
int prime(unsigned n) {
/* check for special cases */
if (n >= 1 && n <= 3) return TRUE; /* all these numbers are prime */
if (n % 2 == 0) return FALSE; /* all these numbers are not */
/* calculate (only once) the rounded down integer square root */
int j, square_root = isqrt(n); /* see below */
for (j = 3; j <= square_root; j += 2) { /* go two by two */
if (n % j == 0)
return FALSE;
}
/* if we reach here, all tests failed, so the number must be prime */
return TRUE;
}
While there's a sqrt() function in <math.h>, I recommend you to write an integer version of the square root routine (you can devise it easily) so you don't need to calculate it in full precision (just to integer precision).
/* the idea of this algorithm is that we have two numbers between 1 and n,
* the greater being the arithmetic mean between the previous two, while
* the lower is the result of dividing the original n by the arithmetic mean.
* it is sure than if we select the arithmetic mean, the number will be
* between the previous ones, and if I divide n by a number that is lower,
* the quotient will be higher than the original number. By the way, the
* arithmetic mean is always bigger than the square root, so the quotient
* will be smaller. At each step, both numbers are closer to each other, and
* so, the smaller is closer to the result of dividing n by itself (and this
* is the square root!)
*/
unsigned isqrt(unsigned n)
{
unsigned geom = 1, arith = n;
while (geom < arith) {
arith = (geom + arith) / 2;
geom = n / arith;
}
/* return the smaller of the two */
return arith;
}
so, your program would be:
#include <stdio.h>
#define FALSE (0)
#define TRUE (!FALSE)
unsigned isqrt(unsigned n)
{
unsigned geom = 1, arith = n;
while (geom < arith) {
arith = (geom + arith) / 2;
geom = n / arith;
}
return arith;
}
int prime(unsigned n) {
/* check for special cases */
if (n >= 1 && n <= 3) return TRUE;
if (n % 2 == 0) return FALSE;
/* calculate (only once) the rounded down integer square root */
int j, square_root = isqrt(n);
for (j = 3; j <= square_root; j += 2) {
if (n % j == 0) {
return FALSE;
}
}
return TRUE;
}
int main() {
unsigned n1, n2, i;
scanf("%u%u", &n1, &n2);
for (i = n1; i <= n2; i++) {
if (prime(i))
printf("%u\n", i);
}
return 0;
}
If you try your version against this one, with values like 2000000000 and 2000000100 you will see how this is saving a lot of calculations (indeed, for the cases below, the case of considering only the odd numbers when going throug the loop will take out of it half the numbers ---this is 1000000000 tests---, but the square root will reduce the number of tests to its square root ---only around 40000 tests--- for each number!!!).
$ primes
2000000000 2000000100
2000000011
2000000033
2000000063
2000000087
2000000089
2000000099
$ _
Your version takes (on my system) this execution time:
$ echo 2000000000 2000100000 | time primes0 >/dev/null
3.09user 0.00system 0:03.09elapsed 99%CPU (0avgtext+0avgdata 1468maxresident)k
0inputs+0outputs (0major+69minor)pagefaults 0swaps
$ _
while the version proposed takes:
$ echo 2000000000 2000100000 | time primes >/dev/null
0.78user 0.00system 0:00.78elapsed 99%CPU (0avgtext+0avgdata 1572maxresident)k
0inputs+0outputs (0major+72minor)pagefaults 0swaps
$ _

a function that works with array elements

I need to write a function that subtracts digits.
If user inputs 2345, the output should be 111 (5-4, 4-3, 3-2); another example would be 683, where the output should be 25 (3-8(abs value is taken), 8-6).
I have wrote the following code which works only when the size of the array is declared.
int subtraction(int arr[], int size) {
int sub = 0;
for (int i = 0; i < size-1; i++) {
sub = sub * 10 + abs(arr[i] - arr[i+1]);
}
return sub;
}
However, the number that the user inputs is random and can have various digits, so I don't know what limit to put in the for loop.
For example:
int arr[] = {1, 2, 55, 56, 65, 135}, i;
subtraction(arr, 6);
for (i=0; i<6; i++)
printf("%d ", arr[i]);
expected output: 0 0 0 1 1 22
The function is supposed to subtract the second-to-last digit from the last one, by the way , / from right to left / from a random number that the user inputs ; for example if the input is 5789, the output is supposed to be 211 (9-8, 8-7, 7-5); if user inputs a negative number, the program should take it's absolute value and then do the subtracting. If user input is a one digit number the result should be 0.
The function I wrote only works when the size of the array is declared. I don't know how to make it work when the size is undeclared (pointers and malloc are required I believe, as that's what I managed to find out by googling for ages, but unfortunately, I don't know how to do it).
please help?
You are not actually changing any values, here is the line you need to look at.
sub = sub * 10 + abs(arr[i] - arr[i+1]);
As you are printing the array you actually need to store the calculated value in the array again.
#include <stdio.h>
#include <stdlib.h>
int subtract(int n)
{
int factor = 1;
int total = 0;
int lastPlace = n%10;
n /= 10;
while (n>0)
{
total += (factor * abs((n%10) - lastPlace));
factor *= 10;
lastPlace = n%10;
n /= 10;
}
return total;
}
void subtractArray(int* arr, unsigned int size)
{
for (int i=0; i<size; ++i)
{
if (arr[i] < 0)
arr[i] = abs(arr[i]);
arr[i] = subtract(arr[i]);
}
}
int main()
{
int arr[] = {1, 2, 55, 56, 65, 135};
int size = sizeof(arr)/ sizeof(arr[0]);
subtractArray(arr, size);
for (int i=0; i<size; ++i)
{
printf("%d ", arr[i]);
}
return 0;
}
Here is a simple code that solve your problem :)
#include <stdio.h>
#include <stdlib.h>
int *subtraction(int arr[], int size)
{
int *sub = calloc(sizeof(int*) , size), i = 0, rev; //allocating memory
for (i = 0; i < size; i++)
{
rev = 0;
arr[i] = abs(arr[i]);
for (int a = 0; arr[i] != 0; arr[i] /= 10)
rev = (rev * 10) + (arr[i] % 10);
for (i; (rev / 10) != 0; rev /= 10) //the loop ends when rev = 0
sub[i] = ((sub[i] * 10) + abs( (rev % 10) - ((rev / 10) % 10) )); //easy math => for example rev = 21 > sub[i] = (0 * 10) + ( (21 % 10) - ((21 / 10) %10)) = abs(1 - 2) = 1;
}
return sub;
}
int main()
{
int arr[] = {-9533, 7, -19173}, i;
int len = sizeof(arr)/sizeof(arr[0]); //size of arr
int *sub = subtraction(arr, len);
for(int i = 0; i < len; i++) //for test
printf("%d ", sub[i]);
return 0;
}
output for {1, 2, 55, 56, 65, 135}:
0 0 0 1 1 22
output for {987654321, 123456789, 111111111} :
11111111 11111111 0
output for {38279}:
5652
output for {-9533, 7, -19173}:
420 0 8864
Well as for the array of undefined size. What you probably want is a dynamically allocated array.
Here we get the number of array elements based on user input, within limits, of course.
first we're gonna get the number from the user using fgets() which will give us a string, then we'll use strtol() to convert the number part to scalar (int). you can use scanf("%d", &n) if you want.
Then we can count the digits from that number, and that value will be the number of elements of our array.
#include <stdio.h>
#include <stdlib.h> //for strtol(), malloc() and NULL guaranteed
//you may also want to add
#include <limits.h>
#include <errno.h>
#define MAX_STRLEN 12 // can hold all digits of INT_MAX plus '\0' and a posible, AND very likely, '\n'
#define DEC 10 // for strtol base argument
/*
* I'm lending you my old get_n_dits() function that I used to count decimal digits.
*/
int get_n_dits(int dnum) {
unsigned char stop_flag = 0; //we'll use to signal we're done with the loop.
int num_dits = 1, dpos_mult = 1; //num_dits start initialized as 1, cause we're pretty sure that we're getting a number with at least one digit
//dpos_mult stands for digital position multiplier.
int check_zresult; //we'll check if integer division yields zero.
/**
* Here we'll iterate everytime (dnum / dpost_mult) results in a non-zero value, we don't care for the remainder though, at least for this use.
* every iteration elevates dpost_mult to the next power of ten and every iteration yielding a non-zero result increments n_dits, once we get
* the zero result, we increment stop_flag, thus the loop condition is no longer true and we break from the loop.
*/
while(!stop_flag) {
dpos_mult *= 10;
check_zresult = dnum / dpos_mult;
(check_zresult) ? num_dits++ : stop_flag++;
}
return num_dits;
}
int main(void) {
int num, ndits; //we'll still using int as per your code. you can check against INT_MAX if you want (defined in limits.h)
int *num_array = NULL; //let's not unintentionally play with an unitialized pointer.
char *num_str = malloc(MAX_STRLEN); //or malloc(sizeof(char) * MAX_STRLEN); if there's any indication that (sizeof(char) != 1)
printf("please enter a number... please be reasonable... or ELSE!\n");
printf(">>> ");
if(!fgets(num_str, MAX_STRLEN, stdin)) {
fprintf(stderr, "Error while reading from STDIN stream.\n");
return -1;
}
num = (int)strtol(num_str, NULL, DEC); //convert the string from user input to scalar.
if(!num) {
fprintf(stderr, "Error: no number found on input.\n");
return -1;
}
ndits = get_n_dits(num);
if(ndits <= 0) {
fprintf(stderr, "Aw, crap!\n");
return -1;
}
printf("number of digits: %d\n", ndits);
num_array = malloc(sizeof(int) * ndits); //now we have our dynamically allocated array.
return 0;
}

How do you write factorial in C?

I need to input this equation and there's a factorial in it. I would like to know if there was something like * = multiplication or pow(1,3) for factorial of something in C.
term = pow(-1, K) * pow(x, 2K)/(2K)
The factorial would be for the last 2K.
Rarely you need a function for computing factorials. Factorials grow so fast that a look-up-table is sufficient for the few values for which the computation does not overflow. If you are computing terms in a loop, you can avoid computing the factorial using an accumulator for the entire term.
K = 0;
term = 1;
while (K<N) {
/* use term */
do_something_with(term);
/* update term for new value of K */
K += 1;
term = -term * x*x / (2*K*(2*K-1));
}
If that seems unclear to you, you can first derive this program where the accumulators are explicit, and then combine the update step into a single variable like above. This program will still have problems with the factorial computation blowing up.
K = 0;
pow_minus_1_K = 1;
pow_x_2K = 1;
factorial_2K = 1;
while (K<N) {
/* compute term */
term = pow_minus_1_K * pow_x_2K/factorial_2K;
/* update accumulators for new value of K */
K += 1;
pow_minus_1_K = -pow_minus_1_K;
pow_x_2K *= x*x;
factorial_2K *= 2*K*(2*K-1);
}
Factorials are easy to calculate, after all n! is just the product of all numbers up to n. But there is a practical problem: Factorials overflow pretty quickly. A 32-bit int can hold 12!, a 64-bit int 20!.
Depending on how your series converges, you might overflow the valid range.
With approximation series like yours, it is usually better to find a means to represent term k by means of term k − 1. In your case:
term = pow(-1, k) * pow(x, 2*k) / fact(2*k)
you can represent a term as
term[k + 1] = -term[k] * pow(x, 2) / ((2*k - 1) * (2*k - 2))
and your series becomes:
double f(double x)
{
double term = 1.0;
double res = term;
int k = 0;
while (k < 100) {
double old = res;
term = -term * (x / (2*k + 1)) * (x / (2*k + 2));
res += term;
if (res == old) break;
k++;
}
return res;
}
This function will use at most 100 iterations to calculate the cosine. It stops when the term doesn't contribute to the result. In practice, it reaches the result with about 10 iterations, so in that case the regular factorial calculations would have been accurate enough. Still, calculating them over and over is wasteful.
There is no predefined function for factorial, but it can be recursively implemented as follows.
int factorial( int a )
{
if ( 0 == a )
return 1;
else
return a * factorial( a - 1 );
}
People who like the ? operator might implement the function as follows.
int factorial( int a )
{
return 0 == a ? 1 : ( a * factorial( a - 1 ) );
}
If a non-recursive formulation is desired, the implementation can be done as follows.
int factorial( int a )
{
int Result = 1;
for ( int i = a; i > 0; Result *= i, i-- );
return Result;
}
If for some reason recursive functions leave you scratching your head, you can also implement it without recursion:
/* calculate n factorial */
unsigned long long nfact (int n)
{
if (n <= 1) return 1;
unsigned long long s = n;
while (--n)
s *= n;
return s;
}
(note: it is up to you to you to implement a test for overflow, if desired)
I think using recursion for this problem is a good way to get started with recursion and understand the way it works, but it's not efficient enough since you're calling a function every time. If you want to know why, do a test and see how long it takes. Although I should say, the iterative method is not significantly better either.
From Code Complete by Steve McConnell:
Don't use recursion for factorials or Fibonacci numbers
One problem with computer-science textbooks is that they present silly
examples of recursion. The typical examples are computing a factorial
or computing a Fibonacci sequence. Recursion is a powerful tool, and
it's really dumb to use it in either of those cases. If a programmer
who worked for me used recursion to compute a factorial, I'd hire
someone else.
So when keep that in mind when going over the recursive versions that are posted here. Now, how to write one.
Basically you have a base case for when the number is less than 1, and a general recursive case. You generally have a base case and a recursive case in a recursive function. For a factorial, it would look something like this:
int factorial_rec(int number)
{
if (number == 0)
{
return 1;
}else
{
return number * factorial_rec(number - 1);
}
}
long fact(int num)
{
if(num==0)
return 1;
else
return num*fact(num-1);
}
Include the above code and call this method to get factorial of a number.
The code to find factorial of a given number using recursive algorithm can be as shown below :
#include<stdio.h>
int fact(int n)
{
if(!n)
return 1;
else
return (n*fact(n-1));
}
void main()
{
int n;
printf("Enter number : ");
scanf("%d",&n);
printf("\nFactorial of %d is : %d",n,fact(n));
}
#include<stdio.h>
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
void main()
{
int number;
long fact;
printf("Enter a number: ");
scanf("%d", &number);
fact = factorial(number);
printf("Factorial of %d is %ld\n", number, fact);
return 0;
}
#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++){
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
return 0;
}
#include <stdio.h>
int main() {
int n, i;
unsigned long long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
// shows error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for (i = 1; i <= n; ++i) {
fact *= i;
}
printf("Factorial of %d = %llu", n, fact);
}
return 0;
}

Function that returns the sum of the number of dividers without remainder of a number, C

I could easily print what I wanted in a loop, but I'm new to functions and I need to save or return the sum of the dividers that have no remainder to a number which is an input of the user.
Example:
Input - 6
Output - 1+2+3=6
How I started:
int NumberOfDividers(int number)
{
int i,num, count = 0;
num = number;
for ( i = 0; i < num; i++)
{
if ((num % i) == 0) //so now I know i is one of the dividers i want to save.
}
}
So if i is one of the dividers I want, how can I save it into a variable? Or an array?
To return the sum of the proper divisors, do:
int sum_of_proper_divisors (int number)
{
int sum = 0;
int i;
for (i = 1; i < number; i++)
{
if ((number % i) == 0)
sum += i;
}
return sum;
}
You just need to use the return keyword to return the value.
You can do this way...
//other headers as you need
#include<string.h>//this header is for memset
int dividers[1000];//global array
int currPos;//global variable
int NumberOfDividers(int number)
{
int i,num, count = 0;
num = number;
for ( i = 1; i < num; i++)//you should start counting from 1 otherwise you will get floating point exception
{
if ((num % i) == 0)
{
dividers[currPos]=i;//putting the dividers in the array
currPos++;//updating the pivot where the next dividers will stay
}
}
return 0;
}
int main()
{
memset(dividers,0,sizeof(dividers));//initializing the array
currPos=0;//initializing the variable to point at the start of the array
NumberOfDividers(6);
int i;
int sum=0;
for(i=0;i<currPos;i++)
{
printf("%d",dividers[i]);
sum+=dividers[i];
if(i!=currPos-1)
{
printf("+");
}
}
printf("=%d\n",sum);
return 0;
}
As this task looked fun to do, did not want to take away the coding experience. Instead laid out a sample algorithm that should code in C fairly directly.
Pseudo-code
int *NumberOfDividers(int number)
find isqrt(number) --> sqrt_number
sqrt_number*2 + 2 --> max_array_count
allocate int[] with max_array_count elements
validate allocation
starting at divisor = 1, in a loop ...
quotient = number/divisor
remainder = number%divisor
if (remainder == 0)
add divisor to list
if (divisor != quotient) add quotient to list
if (divisor >= quotient) quit loop
divisor++
append 0 to list to indicate the end
shrink array to needed size if desired
validate shrink result
return array pointer.
Notice the loop does at most sqrt(number) iterations, so a reasonable upper bound of the needed array size can be calculated before using any divisors.
Also see How many positive integers are factors of a given number? for more advanced ideas.
You can see an another way to do this. This will work very fast for a vast amount of data. Here is my way and you can follow this to find this in a fastest way to find the sum of factors of a number. Here is my code:
int number_of_divisor(int n)
{
int sum_of_factors=0;
sum_of_factors+=1;//as 1 is factor of all num
//sum_of_factors+=n;//n will always a factor of n
for(int i = 2; i * i <= n; ++i)
{
if(n % i == 0)
{
sum_of_factors+=i;
if(i * i != n)
sum_of_factors+=(n/i);
}
}
return sum_of_factors;
}
if your input is long then change all int by long.
Thank you.

First real program in C: Fibonacci sequence

I'm trying to write the first 10 terms of the Fibonacci sequence. I feel like I'm on the right line, but I can't seem to quite grasp the actual code (in C).
float fib = 0;
const float minn = 1;
const float maxn = 20;
float n = minn;
while (n <= maxn);{
n = n + 1;
printf (" %4,2f", fib);
fib = (n - 1) + (n - 2);
}
With the fibonacci sequence the value f(n) = f(n - 1) + f(n = 2). the first three values are defined as 0, 1, 1.
The fibonacci sequence is a sequence of integer values (math integers, not necessarily C language values). consider using int or long for the fibonacci value. float is worthless, it only adds unneeded overhead.
when calculating the fibonacci sequence you must store the previous 2 values to get the next value.
you want 10 fibonacci values. you know the first three already so print those and then calculate the next seven values.
7 values implies a loop that iterates 7 times. it has no bearing on the maximum value of the fibonacci value returned, just how many values you want to print.
do something like this:
printf("0, 1, 1");
int currentValue;
int valueN1 = 1;
int valueN2 = 1;
for (int counter = 1; counter <= 7; ++counter)
{
currentValue = valueN1 + valueN2;
printf(", %d", currentValue);
valueN2 = valueN1;
valueN1 = currentValue;
}
You need run loop 10 times only,to find first 10 terms of the Fibonacci sequence.
in your code,while loop would not let you go further because of semicolon at the end of loop
//declare fib value as long int or unsigned int
// because the value of any fib term is not at all
long int fib;
int n=1;
while (n <= 10)
{
printf (" %d", fib);
fib = fib_term(n);
n = n + 1;
}
implement fib_term(int n); by seeing this snippet
First off, I would suggest changing your datatype from a float to an integer or other datatype. floats are not exact numbers and if you had used while (n = maxn) instead of while (n <= maxn) you could have ended up with an infinite loap since the two floats would never have matched.
Second, you don't seem to really understand what the fibonacci sequence is. Take a look at the wikipedie article http://en.wikipedia.org/wiki/Fibonacci_number.
The fibinocci number is NOT (n - 1) + (n - 2) like you have. It is the sum of the previous two numbers in the sequence. You need to restructure your loop to hold the last two values and calculate the next one based on these values.
There are (at least) 2 ways to implement the Fibonacci Algorithm in C:
The Iterative:
int fib(int n){
if (n == 0)
return 0;
int a = 1
int b = 1;
for (int i = 3; i <= n; i++) {
int c = a + b;
a = b;
b = c;
}
return b;
}
The Recursive:
unsigned int fibonacci_recursive(unsigned int n)
{
if (n == 0)
{
return 0;
}
if (n == 1) {
return 1;
}
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2);
}
void main(){
unsigned int i = fibonacci_recursive(10);
}
Suggestions
Consider integer types before FP types when doing integer problems.
Omit a ; in your while (n <= maxn);{
Use a . in floating point formats %4.2f instead of %4,2f.
Fibonacci is the sum of the previous 2 terms, not simply fib = (n - 1) + (n - 2).
Consider an unsigned solution:
C code:
void Fibonacci_Sequence(unsigned n) {
const unsigned minn = 1;
const unsigned maxn = 20;
unsigned F[3];
F[0] = 0;
F[1] = 1;
unsigned i = 0;
for (i = 0; i <= maxn; i++) {
if (i >= minn) printf(" %u,", F[0]);
F[2] = F[1] + F[0];
F[0] = F[1];
F[1] = F[2];
}
}
This uses n/2 iterations
#include<stdio.h>
main()
{
int i,n,a=0,b=1,odd;
scanf("%d",&n);
odd=n%2;
for(i=1;i<=n/2;i++)
{
printf("%d %d ",a,b);
a=a+b;
b=a+b;
}
if(odd)
printf("%d",a);
}

Resources