C - Powers of a^b for big numbers using Array - c

The question consists of two numbers, a and b, and the answer to it is the sum of digits of a^b.
I have written the below code. It is giving correct result in all cases. But when the input is as such a < b, then after giving the correct answer, I am getting segmentation fault.
I tried a lot to debug it but could not identify the issue. Any help would be greatly appreciated.
Thanks in advance..!
#include<stdio.h>
void power (int, int, int *product);
int main()
{
int a,b,product[200];
scanf("%d %d",&a, &b);
power(a,b,product);
return 0;
}
void power(int a, int b, int *product)
{
int i,m,j,x,temp,sum=0;
int *p = product;
*(p+0)=1; //initializes array with only 1 digit, the digit 1
m=1; // initializes digit counter
temp=0; //Initializes carry variable to 0.
for(i=1;i<=b;i++)
{
for(j=0;j<m;j++)
{
x = (*(p+j))*a+temp;
*(p+j)=x%10;
temp = x/10;
}
while(temp>0) //while loop that will store the carry value on array.
{
*(p+m)=temp%10;
temp = temp/10;
m++;
}
}
//Printing result
for(i=m-1;i>=0;i--)
sum = sum + *(p+i);
printf("\n%d",sum);
printf("\n");
}

I hope the below code does what you are trying to do. Which is simple and looks good too.
#include<stdio.h>
void power (int, int);
int main()
{
int a,b;
scanf("%d %d",&a, &b);
power(a,b);
return 0;
}
void power(int a, int b)
{
int c=1,sum=0;
while(b>0)
{
c = c*a;
b--;
}
printf("%d\n",c);
while(c!=0)
{
sum = sum+(c%10);
c =c/10;
}
printf("%d\n",sum);
}

Related

Getting started on functions need help inputting numbers (beginner)

I was wondering how I can input the numbers using a function with the code written below, and a bit stuck on how I can input and give it an output I am just starting out on functions level 0 at it basically.
int addTwoInt(int a, int b);
int main(void)
{
printf("Enter a number: ");
scanf("%d", &addTwoInt(<#int a#>, <#int b#>));
// printf("The two numbers added are %d", addTwoInt);
}
int addTwoInt(int a, int b)
{
int sum;
sum = a + b;
return sum;
printf("The sum of the numbers are %d", sum);
}
int addTwoInt(int a, int b);
int main(void)
{
int x;
int y;
printf("Enter a number: ");
scanf("%d", &x);
scanf("%d", &y);
int z = addTwoInt(x, y);
printf("%d", z);
//printf("The two numbers added are %d", addTwoInt);
}
int addTwoInt(int a, int b)
{
int sum;
sum = a + b;
printf("The sum of the numbers are %d", sum);
return sum;
}
You asked for cleaner way to add two numbers or other arithmetic operations u can simply do it in return statement just like this:
int addTwoInts(int a, int b){
return a+b
}

Calculate power of all the numbers till n-1

Given n, the program should calculate 1^1 + 2^2 + 3^3 + ... till n-1^n-1. Below is my code, in which there is one function inside while loop which and the passed value is from n-1 in the function. The function definition has two variables which return the ans. Output is wrong always 1.
#include <stdio.h>
#include <stdlib.h>
int power(int x, int y)
{
int la, ans;
if(y==0)
return 1;
else
la= (x*power(x, y-1));
ans+=la;
return ans;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
int n, m, a, b, res, res1;
scanf("%d%d", &n, &m);
while(n-- && n>0)
{
a = power(n-1, n-1);
}
printf("%d", a);
}
return 0;
}
Some problems in your code.
As pointed in another answer, your power function was broken:
ans was not initialized
{ } were missing after the else
in the while, you compute x^x, but you forget the result, whearas you
should sum it.
first thing you do in while loop is to decrease n and to compute power(n-1, n-1)
that sound not logical.
Hence, your corrected code could be:
#include <stdio.h>
#include <stdlib.h>
int power(int x, int y)
{
if(y==0)
return 1;
else
return x*power(x, y-1);
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
int n, m, b, a = 0;
scanf("%d%d", &n, &m);
while(n>1)
{
--n;
b = power(n, n);
a += b;
printf("%d^%d -> %3d\n",n, n, b);
}
printf("sum= %d", a);
}
return 0;
}
Gives for n = 6:
5^5 -> 3125
4^4 -> 256
3^3 -> 27
2^2 -> 4
1^1 -> 1
sum=3413
C uses braces to form blocks, your power() function looks like it's wanting to use indentation like in Python.
It should probably be:
int power(int x, int y)
{
int la, ans;
if(y==0)
return 1;
else
{
la= (x*power(x, y-1));
ans+=la;
return ans;
}
}
Of course since the first if has a return, the else is pointless, and you can simplify the code:
int power(int x, int y)
{
if (y==0)
return 1;
return x * power(x, y-1);
}
The variable ans was never assigned to, that looked broken so I simplified it out.
Of course this is susceptible to integer overflow.

Factorial using pointers in C program

I want to create a program to find the factorial of a number also I want to make it using pointers.
I have tried to make a program but it is not giving the factorial of the number . Can anybody explains me why ?
#include<stdio.h>
#include<stdlib.h>
int fact(int* num, int* n)
{
for ((*n) = 1; (*n) <= (*num); (*n)++)
{
*n = (*n)*(*num);
}
}
int main()
{
int num, n;
printf("Write the number to take factorial \n");
scanf("%d", &num);
fact(&num, &n);
printf("Factorial = %d", n);
return 0;
}
As you are using int function it must contain some return value. If you make following changes it runs perfectly.
#include <stdio.h>
#include <stdlib.h>
int fact(int *num, int *n)
{
long long unsigned int fact = 1;
for ((*n) = 1; (*n) <= (*num); (*n)++)
{
fact = fact * (*n);
}
return fact;
}
int main()
{
int num, n;
long long unsigned int b;
printf("Write the number to take factorial \n");
scanf("%d", &num);
b = fact( &num, &n);
printf("Factorial = %llu", b);
return 0;
}
*n=(*n)*(*num); is changing the value of the counting variable used in the for loop!
Whilst this is perfectly legal in C, it's leading to the incorrect answer.
You also don't return a value explicitly from fact despite it having a non-void return type. That's undefined behaviour.
Note also that the range for an int can be as small as -32767 to +32767, which only allows for 7! or lower. Consider using a long long type instead.
Correct me if I am wrong, but I think the logic itself is incorrect in your attempt :
for ((*n) = 1; (*n) <= (*num); (*n)++)
{
*n = (*n)*(*num);
}
You are using the counting variable ('*n' in this case) for purpose of storing the result. If you check the flow the loop will end after first iteration then increment it giving you the value of (*num + 1).
A good modification for your fact function could be :
void fact(int* num, int* n)
{
int counter;
*n=1;
for (counter = 2 ; counter <= (*num) ; counter++)
{
*n = (*n)*(counter);
}
}
Can't see a reason to keep the return type of the function as int if you are using call by reference for the result as well.
As in response to answer given by '#nikhil biijjala' , I can't understand your reason to pass the pointer (*n) in the first place.All that pointer does is works as a local counter for the loop.
As in case of large integers you can add limits to input or use long long.
C++ Version:
#include <iostream>
int abc(int *a);
int main()
{
int a,fact;
int *ptr;
std::cout << "Enter a:"<< std::endl;
std::cin >> a;
ptr= &a;
fact=*ptr;
while(*ptr!=1)
{
fact = fact * abc(ptr);
}
std::cout << "Factorial is : <<" << fact << std::endl;
return 0;
}
int abc(int *a)
{
*a=*a-1;
return *a;
}
#include<stdio.h>
int facto(int *);
int main()
{
int factorial, v;
printf("Enter the value : ");
scanf("%d", &v);
factorial = facto(&v);
printf("The factorial of %d is %d.\n", v, factorial);
}
int facto(int *p)
{
int c;
c = *p - 1;
if (*p == 1)
return 1;
else
return (*p) * (facto(&c));
}

How to print this series x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!) in C/C++?

I wish to write a program which calculates the series x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!) by taking x and n as user inputs.
This is what i've tried, and well there's no output when I enter the values for x,n:
#include<stdio.h>
#include<math.h>
//#include<process.h>
#include<stdlib.h>
double series(int,int);
double factorial(int);
int main()
{
double x,n,res;
printf("This program will evaluate the following series:\nx-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf("\nPlease enter a value for x and an odd value for n\n");
scanf("%lf%lf",&x,&n);
/*if(n%2!=0)
{
printf("Please enter a positive value!\n");
exit(0);
}*/
res=series(x,n);
printf("For the values you've entered, the value of the series is:\n %lf",res);
}
double series(int s, int t)
{
int i,sign=1; double r,fact,exec;
for(i=1;i<=t;i+2)
{
exec=sign*(pow(s,i)/factorial(i));
r+=exec;
sign*=-1;
}
return r;
}
double factorial(int p)
{
double f=1.0;
while(p>0)
{
f*=p;
p--;
}
return f;
}
When I enter values for x and n, it simply shows nothing.
While I've written in C, C++ solutions are also appreciated.
Output window in code::blocks
The loop
for(i=1;i<=t;i+2)
in the function series() is an infinite loop when t >= 1 because i isn't updated in the loop. Try changing + to += and use
for(i=1;i<=t;i+=2)
instead. Also it seems you should use type int for x and n in the function main() because the arguments of series() is int. Don't forget to change the format specifier when changing their types.
Thanks to all those who helped. Here's the final working code:
#include<stdio.h>
#include<math.h>
#include<process.h>
#include<stdlib.h>
double series(int,int);
double factorial(int);
int main()
{
int x,n; double res;
printf("This program will evaluate the following series:\nx-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf("\nPlease enter a value for x and an odd value for n\n");
scanf("%d%d",&x,&n);
if(n%2==0)
{
n=n-1;
}
res=series(x,n);
printf("For the values you've entered, the value of the series is:\n%lf",res);
}
double series(int s, int t)
{
int i,sign=1; double r=0.0,fact,exec;
for(i=1;i<=t;i+=2)
{
exec=sign*(pow(s,i)/factorial(i));
r+=exec;
sign*=-1;
}
return r;
}
double factorial(int p)
{
double f=1;
while(p>0)
{
f*=p;
p--;
}
return f;
}
in loop we step by two for getting odd numbers.by multiplying the current temp variable by the previous temp variable in the loop with neccesary terms like x square and dividing by i*(i-1) i.e for factorial and multiply with -1 i.e to achive negavtive number alternatively. by using this temp variable and adding it to sum variable in every iteration will give us answer.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n, x;
cout << "enter x and no.of terms: ";
cin >> x >> n;
float sum = 0, temp = x;
for (int i = 3; i < 2 * n + 2; i = i + 2)
{
temp = ((-1 * temp) *(x*x)) / i*(i-1);
sum = sum + temp;
}
cout << x + sum;
return 0;
}
// series x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)
#include<stdio.h>
#include<math.h>
double factorial (int);
double calc (float, float);
int
main ()
{
int x, deg;
double fin;
printf ("x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf ("Enter value of x\n");
scanf ("%d", &x);
printf ("highest degree in denom i.e., 1 or 3 or 5 whatever, it should be odd .\n");
scanf ("%d", &deg);
fin = calc (x, deg);
printf ("the summation of series =%1f\n", fin);
return 0;
}
double calc (float num, float res)
{
int count, sign = 1;
double rres = 0;
for (count = 1; count <= res; count += 2)
{
rres += sign * (pow (num, count) / factorial (count));
sign *= -1;
}
return (rres);
}
double factorial (int num)
{
int count;
double sum = 1;
for (count = 1; count <= num; count++)
{
sum *= count;
}
return (sum);
}

Adding multiple integers using arguments in function

I am learning function in C. I want to sum multiple integers using arguments in function. I managed to write a code for adding two integers, but how if I want to add multiple integers and print the total of them? please guide me. Code which i wrote is;
#include<stdio.h>
#include<conio.h>
int sum(int a, int b, int c);
int main (void){
int x,y,z;
clrscr();
printf("Enter first integer to add.\n");
scanf("%d",&x);
printf("Enter second integer to add.\n");
scanf("%d",&y);
sum(x, y, z);
printf("Total = %d.\n",sum(x, y, z));
getch();
return 0;
}
int sum (int a, int b, int c){
c=a+b;
return c;
}
You can do something like this.
sum = 0;
while (ch == "y")
{
scanf("%d", &a);
sum+=a;
printf("Do you want to continue: ");
scanf("%c\n", &ch);
}
printf("%d", sum);
The idea is to have a variable sum whose initial value is 0.
Have a while loop that takes a integer a as input & add it to sum.
You can mantain a variable ch, which can be used to exit out of the loop. Only if the user enters "y", the user will be asked for integer again.
try this !
int main()
{
int var[100];
int count = 5;
printf("enter number %d number ", count);
for( int i = 0; i < count; i++ )
{
scanf( "%d", &var[i] );
}
printf("sum=%d", sum(var, count) );
return 0;
}
int sum( int var[], int count )
{
int sum = 0;
for( int i = 0; i < count; i++ )
{
sum += var[i];
}
return sum;
}
Currently you're overwriting the third argument to the function with the sum of the first two and return it. This should probably change a bit.
Just think about how you'd write a sum of three numbers in mathematics and you should see the solution.

Resources