Arithmetic Progression - GeeksforGeeks (2024)

Last Updated : 29 Jul, 2024

Comments

Improve

Summarize

Suggest changes

Like Article

Like

Save

Report

A sequence of numbers is called an Arithmetic progression if the difference between any two consecutive terms is always the same.

In simple terms, it means that the next number in the series is calculated by adding a fixed number to the previous number in the series.

Example:

Sequence 1, 4, 7,10 is an AP because the difference between any two consecutive terms in the series (common difference) is the same.

The difference between 2nd and 1st term 4 – 1 = 3
The difference between 3rd and 2nd term 7 – 4 = 3
The difference between 4th and 3rd term10 – 7 = 3

Arithmetic Progression - GeeksforGeeks (2)

From the above example, we can conclude that there is some common difference between any two consecutive elements.

Notation in Arithmetic Progression

In AP, there are some main terms that are generally used, which are denoted as:

  • Initial term (a): In an arithmetic progression, the first number in the series is called the initial term.
  • Common difference (d): The value by which consecutive terms increase or decrease is called the common difference. The behavior of the arithmetic progression depends on the common difference d. If the common difference is: positive, then the members (terms) will grow towards positive infinity or negative, then the members (terms) will grow towards negative infinity.
  • nth Term (an): The nth term of the AP series
  • Sum of the first n terms (Sn): The sum of the first n terms of the AP series.

The formula for the nth term of an A.P:

If ‘a’ is the initial term and ‘d’ is a common difference. Thus, the explicit formula is

Arithmetic Progression - GeeksforGeeks (3)

The formula for the sum of n terms of AP:

Arithmetic Progression - GeeksforGeeks (4)

How do we check whether a series is an arithmetic progression or not?

1. Brute approach.

The idea is to sort the given array or series. After sorting, check if the differences between consecutive elements are the same or not. If all differences are the same, Arithmetic Progression is possible.

Below is the implementation of this approach:

C++
// C++ program to check if a given array// can form arithmetic progression#include <bits/stdc++.h>using namespace std;// Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionbool checkIsAP(int arr[], int n){ if (n == 1) return true; // Sort array sort(arr, arr + n); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true;}// Driven Programint main(){ int arr[] = { 20, 15, 5, 0, 10 }; int n = sizeof(arr) / sizeof(arr[0]); (checkIsAP(arr, n)) ? (cout << "Yes" << endl) : (cout << "No" << endl); return 0;}
Java
// Java program to check if a given array// can form arithmetic progressionimport java.util.Arrays;class GFG { // Returns true if a permutation of // arr[0..n-1] can form arithmetic // progression static boolean checkIsAP(int arr[], int n) { if (n == 1) return true; // Sort array Arrays.sort(arr); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true; } // driver code public static void main(String[] args) { int arr[] = { 20, 15, 5, 0, 10 }; int n = arr.length; if (checkIsAP(arr, n)) System.out.println("Yes"); else System.out.println("No"); }}// This code is contributed by Anant Agarwal.
Python3
# Python3 program to check if a given # array can form arithmetic progression# Returns true if a permutation of arr[0..n-1]# can form arithmetic progressiondef checkIsAP(arr, n): if (n == 1): return True # Sort array arr.sort() # After sorting, difference between # consecutive elements must be same. d = arr[1] - arr[0] for i in range(2, n): if (arr[i] - arr[i-1] != d): return False return True# Driver codearr = [ 20, 15, 5, 0, 10 ]n = len(arr)print("Yes") if(checkIsAP(arr, n)) else print("No")# This code is contributed by Anant Agarwal.
C#
// C# program to check if a given array// can form arithmetic progressionusing System;class GFG { // Returns true if a permutation of // arr[0..n-1] can form arithmetic // progression static bool checkIsAP(int[] arr, int n) { if (n == 1) return true; // Sort array Array.Sort(arr); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true; } // Driver Code public static void Main() { int[] arr = { 20, 15, 5, 0, 10 }; int n = arr.Length; if (checkIsAP(arr, n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }}// This code is contributed by vt_m.
JavaScript
<script>// Javascript program to check if a given array// can form arithmetic progression// Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionfunction compare(a, b) { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; }}function checkIsAP( arr, n){ if (n == 1) return true; // Sort array arr.sort(compare); // After sorting, difference between // consecutive elements must be same. let d = arr[1] - arr[0]; for (let i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true;}// Driven Programlet arr = [ 20, 15, 5, 0, 10 ];let n = arr.length;(checkIsAP(arr, n)) ? document.write("Yes <br>") : document.write("No <br>");</script>
PHP
<?php// PHP program to check if // a given array can form// arithmetic progression// Returns true if a permutation // of arr[0..n-1] can form // arithmetic progressionfunction checkIsAP($arr, $n){ if ($n == 1) return true; // Sort array sort($arr); // After sorting, difference // between consecutive elements // must be same. $d = $arr[1] - $arr[0]; for ($i = 2; $i < $n; $i++) if ($arr[$i] - $arr[$i - 1] != $d) return false; return true;}// Driver Code$arr = array(20, 15, 5, 0, 10);$n = count($arr);if(checkIsAP($arr, $n))echo "Yes"; elseecho "No"; // This code is contributed // by Sam007?>

Output

Yes

Time Complexity: O(n Log n).
Auxiliary Space: O(1)

2. Efficient solutions

  • Set 1(Use Hashing)
  • Set 2(Use Counting Sort)

Basic Program related to Arithmetic Progression

  • Program for sum of arithmetic series
  • Program to print Arithmetic Progression series
  • Longest arithmetic progression with the given common difference
  • Check whether Arithmetic Progression can be formed from the given array
  • Find the missing number in Arithmetic Progression
  • Find N Arithmetic Means between A and B
  • Sum of the numbers upto N that are divisible by 2 or 5
  • Find First element in AP which is multiple of given prime

More problems related to Arithmetic Progression

  • Sum of first n terms of a given series 3, 6, 11, …..
  • Ratio of mth and nth terms of an A. P. with given ratio of sums
  • Probability for three randomly chosen numbers to be in AP
  • Print all triplets in sorted array that form AP
  • Program for N-th term of Arithmetic Progression series
  • Sum of Arithmetic Geometric Sequence
  • Count of AP (Arithmetic Progression) Subsequences in an array


Recent Articles on Arithmetic Progression!



`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } document.getElementById('article-video-tab-content').style.display = 'block'; } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); // error handling for no compatible source player.on('error', function() { var error = player.error(); console.log("Video Error: ", error); if (error && error.code === 4) { console.log("No compatible source was found for this media."); hideVideoPlayer(); } }); }, function(err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); hideVideoPlayer(); // hiding video in case of timeout (requirejs) console.log(err); }); // function to hide the video player function hideVideoPlayer() { var videoPlayer = document.getElementById('article-video'); if (videoPlayer) { videoPlayer.parentNode.removeChild(videoPlayer); } } /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content // element = document.getElementById('article-video-tab-content'); // element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Arithmetic Progression - GeeksforGeeks (2024)

References

Top Articles
It's been another bad quarter for the fast-food industry. Burgers and pizza are too expensive, and Americans just don't want to splash out.
Hunter X Athena Script Pastebin
The Blackening Showtimes Near Century Aurora And Xd
Week 2 Defense (DEF) Streamers, Starters & Rankings: 2024 Fantasy Tiers, Rankings
Restaurer Triple Vitrage
Farepay Login
Mychart Mercy Lutherville
Craigslist Motorcycles Jacksonville Florida
The Realcaca Girl Leaked
South Carolina defeats Caitlin Clark and Iowa to win national championship and complete perfect season
Nyuonsite
Aita Autism
Valentina Gonzalez Leaked Videos And Images - EroThots
Craigslist Jobs Phoenix
Bros Movie Wiki
Regal Stone Pokemon Gaia
Diablo 3 Metascore
Craigslist Pets Sac
Help with Choosing Parts
Salem Oregon Costco Gas Prices
Inside the life of 17-year-old Charli D'Amelio, the most popular TikTok star in the world who now has her own TV show and clothing line
Selfservice Bright Lending
Aol News Weather Entertainment Local Lifestyle
Loslaten met de Sedona methode
Pioneer Library Overdrive
The Clapping Song Lyrics by Belle Stars
Stephanie Bowe Downey Ca
Rugged Gentleman Barber Shop Martinsburg Wv
Primerica Shareholder Account
Hoofdletters voor God in de NBV21 - Bijbelblog
Landing Page Winn Dixie
Ellafeet.official
Aladtec Login Denver Health
Bratislava | Location, Map, History, Culture, & Facts
Worlds Hardest Game Tyrone
Free Robux Without Downloading Apps
PA lawmakers push to restore Medicaid dental benefits for adults
Zero Sievert Coop
SOC 100 ONL Syllabus
Robeson County Mugshots 2022
Culvers Lyons Flavor Of The Day
Weather Underground Bonita Springs
Yogu Cheshire
Skyward Marshfield
Fool's Paradise Showtimes Near Roxy Stadium 14
Academic Calendar / Academics / Home
Large Pawn Shops Near Me
DL381 Delta Air Lines Estado de vuelo Hoy y Historial 2024 | Trip.com
Slug Menace Rs3
Tìm x , y , z :a, \(\frac{x+z+1}{x}=\frac{z+x+2}{y}=\frac{x+y-3}{z}=\)\(\frac{1}{x+y+z}\)b, 10x = 6y và \(2x^2\)\(-\) \(...
What your eye doctor knows about your health
Adams County 911 Live Incident
Latest Posts
Article information

Author: Allyn Kozey

Last Updated:

Views: 6122

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.