Thursday, 16 March 2017

Geeksforgeeks Solution For " Sum of an AP "

GeeksforGeeks Solution For School Domain .Below You Can Find The Solution Of Basic ,Easy ,Medium ,Hard .You Can Also Direct Submit Your Solution to Geeksforgeeks Same Problem .You Need to login then you can submit you answers 

Problem :- Write a program to print sum of an AP with n terms with first term a and common difference d.

Submit Your Solution :- Click Here 


Solution :- 

Method 1 :-

#include <iostream>
using namespace std;
int main() 
{
int t;
cin>>t;
while(t--)
{
   int n,a,b,d,sum=0;
   cin>>n;
   cin>>a>>d;
   sum=(n*((2*a)+((n-1)*d)))/2;
   cout<<sum<<endl;
}
return 0;
}

Method 2 :-

#include <iostream>
#include<cstdio>
#include <cmath>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
       int n,a,p,r;
       long double sum=0.0;
       cin>>n;
       cin>>a>>r;
       if(r==1){
           cout<<a*n<<endl;
           continue;
       }
       p=pow(r,n);
       sum=(a*(1-p)/(1-r));
       sum/=1.0;
       //cout<<sum<<endl;
       printf("%Lf\n", sum);

    }
    return 0;

}

Method 3 :-

#include <stdio.h>
#include <math.h>

double GP(int a, int r, int n) 
{
    return (a*pow(r,n)-a)/(r-1);
}
int main() 
{
  int t;
  scanf("%d",&t);
  while(t--)
  {
      double N, i, a, r;
      scanf("%lf\n",&N);
      scanf("%lf %lf",&a,&r);
      if(r==1)
      {
          printf("%lf\n",a*N);
      }
      else 
      {
      printf("%lf\n", GP(a, r, N));
      }
  }
  return 0;

}

Output:-

Geeksforgeeks Solution For " Sum of an AP "

No comments:
Write comments

Recommended Posts × +