Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • DSA
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
Count ways to represent a number as sum of perfect squares
Next article icon

Count ways to represent a number as sum of perfect squares

Last Updated : 06 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer N, the task is to find the number of ways to represent the number N as sum of perfect squares.

Examples:

Input: N = 9
Output: 4
Explanation:
There are four ways to represent 9 as the sum of perfect squares:
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 9
1 + 1 + 1 + 1 + 1 + 4 = 9
1 + 4 + 4 = 9
9 = 9

Input: N = 8
Output: 3

 

Naive Approach: The idea is to store all the perfect squares less than or equal to N in an array. The problem now reduces to finding the ways to sum to N using array elements with repetition allowed which can be solved using recursion. Follow the steps below to solve the problem:

  • Store all the perfect squares less than or equal to N and in an array psquare[].
  • Create a recursion function countWays(index, target) that takes two parameters index, (initially N-1) and target (initially N):
    • Handle the base cases:
      • If the target is 0, return 1.
      • If either index or target is less than 0, return 0.
    • Otherwise, include the element, psquare[index] in the sum by subtracting it from the target and recursively calling for the remaining value of target.
    • Exclude the element, psquare[index] from the sum by moving to the next index and recursively calling for the same value of target.
    • Return the sum obtained by including and excluding the element.
  • Print the value of countWays(N-1, N) as the result.

Below is the implementation of the above approach:

C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

// Store perfect squares
// less than or equal to N
vector<int> psquare;

// Utility function to calculate perfect
// squares less than or equal to N
void calcPsquare(int N)
{
    for (int i = 1; i * i <= N; i++)
        psquare.push_back(i * i);
}

// Function to find the number
// of ways to represent a number
// as sum of perfect squares
int countWays(int index, int target)
{
    // Handle the base cases
    if (target == 0)
        return 1;

    if (index < 0 || target < 0)
        return 0;

    // Include the i-th index element
    int inc = countWays(
        index, target - psquare[index]);

    // Exclude the i-th index element
    int exc = countWays(index - 1, target);

    // Return the result
    return inc + exc;
}

// Driver Code
int main()
{
    // Given Input
    int N = 9;

    // Precalculate perfect
    // squares <= N
    calcPsquare(N);

    // Function Call
    cout << countWays(psquare.size() - 1, N);

    return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;

public class GFG {

    // Store perfect squares
    // less than or equal to N
    static ArrayList<Integer> psquare = new ArrayList<>();

    // Utility function to calculate perfect
    // squares less than or equal to N
    static void calcPsquare(int N)
    {
        for (int i = 1; i * i <= N; i++)
            psquare.add(i * i);
    }

    // Function to find the number
    // of ways to represent a number
    // as sum of perfect squares
    static int countWays(int index, int target)
    {
        // Handle the base cases
        if (target == 0)
            return 1;

        if (index < 0 || target < 0)
            return 0;

        // Include the i-th index element
        int inc
            = countWays(index, target - psquare.get(index));

        // Exclude the i-th index element
        int exc = countWays(index - 1, target);

        // Return the result
        return inc + exc;
    }

    // Driver Code
    public static void main(String[] args)
    {
        // Given Input
        int N = 9;

        // Precalculate perfect
        // squares <= N
        calcPsquare(N);

        // Function Call
        System.out.print(countWays(psquare.size() - 1, N));
    }
}

// This code is contributed by Kingash.
Python3
# Python3 program for the above approach

# Store perfect squares
# less than or equal to N
psquare = []

# Utility function to calculate perfect
# squares less than or equal to N
def calcPsquare(N):
    
    for i in range(1, N):
        if i * i > N:
            break
        
        psquare.append(i * i)

# Function to find the number
# of ways to represent a number
# as sum of perfect squares
def countWays(index, target):
    
    # Handle the base cases
    if (target == 0):
        return 1

    if (index < 0 or target < 0):
        return 0

    # Include the i-th index element
    inc = countWays(index, target - psquare[index])

    # Exclude the i-th index element
    exc = countWays(index - 1, target)

    # Return the result
    return inc + exc

# Driver Code
if __name__ == '__main__':
    
    # Given Input
    N = 9

    # Precalculate perfect
    # squares <= N
    calcPsquare(N)

    # Function Call
    print (countWays(len(psquare) - 1, N))

# This code is contributed by mohit kumar 29
C#
using System.IO;
using System;
using System.Collections;

class GFG {
    // Store perfect squares
    // less than or equal to N
    static ArrayList psquare = new ArrayList();

    // Utility function to calculate perfect
    // squares less than or equal to N
    static void calcPsquare(int N)
    {
        for (int i = 1; i * i <= N; i++)
            psquare.Add(i * i);
    }

    // Function to find the number
    // of ways to represent a number
    // as sum of perfect squares
    static int countWays(int index, int target)
    {
        // Handle the base cases
        if (target == 0)
            return 1;

        if (index < 0 || target < 0)
            return 0;

        // Include the i-th index element
        int inc = countWays(index,
                            target - (int)psquare[index]);

        // Exclude the i-th index element
        int exc = countWays(index - 1, target);

        // Return the result
        return inc + exc;
    }

    static void Main()
    {
      
        // Given Input
        int N = 9;

        // Precalculate perfect
        // squares <= N
        calcPsquare(N);

        // Function Call
        Console.WriteLine(countWays(psquare.Count - 1, N));
    }
}

// This code is contributed by abhinavjain194.
JavaScript
<script>

// JavaScript program for the above approach

// Store perfect squares
// less than or equal to N
var psquare = []

// Utility function to calculate perfect
// squares less than or equal to N
function calcPsquare(N)
{
    var i;
    for (i = 1; i * i <= N; i++)
        psquare.push(i * i);
}

// Function to find the number
// of ways to represent a number
// as sum of perfect squares
function countWays(index, target)
{
    // Handle the base cases
    if (target == 0)
        return 1;

    if (index < 0 || target < 0)
        return 0;

    // Include the i-th index element
    var inc = countWays(
        index, target - psquare[index]);

    // Exclude the i-th index element
    var exc = countWays(index - 1, target);

    // Return the result
    return inc + exc;
}

// Driver Code
    // Given Input
    var N = 9;

    // Precalculate perfect
    // squares <= N
    calcPsquare(N);

    // Function Call
    document.write(countWays(psquare.length - 1, N));

</script>

Output: 
4

 

Time Complexity: O(2K), where K is the number of perfect squares less than or equal to N
Auxiliary Space: O(1)

Efficient approach: This problem has overlapping subproblems and optimal substructure property. To optimize the above approach, the idea is to use dynamic programming by memoizing the above recursive calls using a 2D array of size K*N, where K is the number of perfect squares less than or equal to N.

Below is the implementation of the above approach: 

C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

// Store perfect squares
// less than or equal to N
vector<int> psquare;

// Utility function to calculate
// perfect squares <= N
void calcPsquare(int N)
{
    for (int i = 1; i * i <= N; i++)
        psquare.push_back(i * i);
}

// DP array for memoization
vector<vector<int> > dp;

// Recursive function to count
// number of ways to represent
// a number as a sum of perfect squares
int countWaysUtil(int index, int target)
{
    // Handle base cases
    if (target == 0)
        return 1;
    if (index < 0 || target < 0)
        return 0;

    // If already computed, return the result
    if (dp[index][target] != -1)
        return dp[index][target];

    // Else, compute the result
    return dp[index][target]
           = countWaysUtil(
                 index, target - psquare[index])

             + countWaysUtil(
                   index - 1, target);
}

// Function to find the number of ways to
// represent a number as a sum of perfect squares
int countWays(int N)
{
    // Precalculate perfect squares less
    // than or equal to N
    calcPsquare(N);

    // Create dp array to memoize
    dp.resize(psquare.size() + 1,
              vector<int>(N + 1, -1));

    // Function call to fill dp array
    return countWaysUtil(psquare.size() - 1, N);
}

// Driver Code
int main()
{
    // Given Input
    int N = 9;

    // Function Call
    cout << countWays(N);

    return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;

public class GFG {
    
    // Store perfect squares
    // less than or equal to N
    private static ArrayList<Integer> psquare;

    
    // Utility function to calculate
    // perfect squares <= N
    private static void calcPsquare(int n) {

        for (int i = 1; i * i <= n; i++)
            psquare.add(i * i);
        
    }
    
    // DP array for memoization
    private static int[][] dp;
    
    // Recursive function to count
    // number of ways to represent
    // a number as a sum of perfect squares
    private static int countWaysUtil(int index, int target) {
        // Handle base cases
        if (target == 0)
            return 1;
        if (index < 0 || target < 0)
            return 0;
     
        // If already computed, return the result
        if (dp[index][target] != -1)
            return dp[index][target];
     
        // Else, compute the result
        return dp[index][target]
               = countWaysUtil(
                     index, target - psquare.get(index))
     
                 + countWaysUtil(
                       index - 1, target);
    }
    
    // Function to find the number of ways to
    // represent a number as a sum of perfect squares
    private static int countWays(int n) {
        // Precalculate perfect squares less
        // than or equal to N
        psquare = new ArrayList<Integer>();
        calcPsquare(n);
     
        // Create dp array to memoize
        dp = new int[psquare.size()+1][n+1];
        for(int i = 0; i<=psquare.size(); i++)Arrays.fill(dp[i], -1);
     
        // Function call to fill dp array
        return countWaysUtil(psquare.size() - 1, n);
    }



    // Driver Code
    public static void main(String[] args)
    {
        // Given Input
        int N = 9;

        // Function Call
        System.out.print(countWays(N));
    }
    
}

// This code is contributed by Dheeraj Bhagchandani.
Python3
# Python3 program for the above approach
from math import sqrt

# Store perfect squares
# less than or equal to N
psquare = []

# DP array for memoization
dp = []

# Utility function to calculate
# perfect squares <= N
def calcPsquare(N):
    
    global psquare
    for i in range(1, int(sqrt(N)) + 1, 1):
        psquare.append(i * i)

# Recursive function to count
# number of ways to represent
# a number as a sum of perfect squares
def countWaysUtil(index, target):
    
    global dp
    
    # Handle base cases
    if (target == 0):
        return 1
    if (index < 0 or target < 0):
        return 0

    # If already computed, return the result
    if (dp[index][target] != -1):
        return dp[index][target]

    dp[index][target] = (countWaysUtil(
                               index, target - psquare[index]) + 
                         countWaysUtil(index - 1, target))

    # Else, compute the result
    return dp[index][target]

# Function to find the number of ways to
# represent a number as a sum of perfect squares
def countWays(N):
    
    global dp
    global psquare
    
    # Precalculate perfect squares less
    # than or equal to N
    calcPsquare(N)
    temp = [-1 for i in range(N + 1)]
    
    # Create dp array to memoize
    dp = [temp for i in range(len(psquare) + 1)]

    # Function call to fill dp array
    return countWaysUtil(len(psquare) - 1, N) - 1

# Driver Code
if __name__ == '__main__':
    
    # Given Input
    N = 9
    
    # Function Call
    print(countWays(N))

# This code is contributed by ipg2016107
C#
// C# program for the above approach
using System;
using System.Collections.Generic;

class GFG{
    
// Store perfect squares
// less than or equal to N
static List<int> psquare;

// Utility function to calculate
// perfect squares <= N
private static void calcPsquare(int n) 
{
    for(int i = 1; i * i <= n; i++)
        psquare.Add(i * i);
}

// DP array for memoization
private static int[,]dp;

// Recursive function to count
// number of ways to represent
// a number as a sum of perfect squares
private static int countWaysUtil(int index,
                                 int target) 
{
    
    // Handle base cases
    if (target == 0)
        return 1;
    if (index < 0 || target < 0)
        return 0;
 
    // If already computed, return the result
    if (dp[index, target] != -1)
        return dp[index, target];
 
    // Else, compute the result
    return dp[index, target] = countWaysUtil(index, 
                                             target - psquare[index]) + 
                               countWaysUtil(index - 1, target);
}

// Function to find the number of ways to
// represent a number as a sum of perfect squares
private static int countWays(int n)
{
    
    // Precalculate perfect squares less
    // than or equal to N
    psquare = new List<int>();
    calcPsquare(n);
 
    // Create dp array to memoize
    dp = new int[psquare.Count + 1, n + 1];
    for(int i = 0; i <= psquare.Count; i++)
    {
        for(int j = 0; j <= n; j++)
        {
            dp[i, j] = -1;
        }
        
        //Array.Fill(dp[i], -1);
    }
 
    // Function call to fill dp array
    return countWaysUtil(psquare.Count - 1, n);
}

// Driver Code
static void Main() 
{
    
    // Given Input
    int N = 9;

    // Function Call
   Console.Write(countWays(N));
}
}

// This code is contributed by SoumikMondal
JavaScript
<script>

// JavaScript program for the above approach

let psquare;

function calcPsquare(n)
{
     for (let i = 1; i * i <= n; i++)
            psquare.push(i * i);
}

 // DP array for memoization
let dp;

// Recursive function to count
    // number of ways to represent
    // a number as a sum of perfect squares
function countWaysUtil(index,target)
{
    // Handle base cases
        if (target == 0)
            return 1;
        if (index < 0 || target < 0)
            return 0;
      
        // If already computed, return the result
        if (dp[index][target] != -1)
            return dp[index][target];
      
        // Else, compute the result
        return dp[index][target]
               = countWaysUtil(
                     index, target - psquare[index])
      
                 + countWaysUtil(
                       index - 1, target);
}

// Function to find the number of ways to
    // represent a number as a sum of perfect squares
function countWays(n)
{
    // Precalculate perfect squares less
        // than or equal to N
        psquare = [];
        calcPsquare(n);
      
        // Create dp array to memoize
        dp = new Array(psquare.length+1);
        for(let i=0;i<psquare.length+1;i++)
        {
            dp[i]=new Array(n+1);
            for(let j=0;j<n+1;j++)
            {
                dp[i][j]=-1;
            }
        }
        
      
        // Function call to fill dp array
        return countWaysUtil(psquare.length - 1, n);
}

// Driver Code
// Given Input
let N = 9;

// Function Call
document.write(countWays(N));


// This code is contributed by patel2127

</script>

Output
4

Time Complexity: O(K*N), where K is the number of perfect squares less than or equal to N
Auxiliary Space: O(K*N)


 


Next Article
Count ways to represent a number as sum of perfect squares
author
saikumarkudikala
Improve
Article Tags :
  • Searching
  • Mathematical
  • Recursion
  • DSA
  • maths-perfect-square
Practice Tags :
  • Mathematical
  • Recursion
  • Searching

Similar Reads

    Count of ways to represent N as sum of a prime number and twice of a square
    Given an integer N, the task is to count the number of ways so that N can be written as the sum of a prime number and twice of a square, i.e. N = 2*A^{2} + P , where P can be any prime number and A is any positive integer. Note: N <= 10^{6} Examples: Input: N = 9 Output: 1 Explanation: 9 can be r
    8 min read
    Print n numbers such that their sum is a perfect square
    Given an integer n, the task is to print n numbers such that their sum is a perfect square.Examples: Input: n = 3 Output: 1 3 5 1 + 3 + 5 = 9 = 32 Input: n = 4 Output: 1 3 5 7 1 + 3 + 5 + 7 = 16 = 42 Approach: The sum of first n odd numbers is always a perfect square. So, we will print the first n o
    3 min read
    Check whether a number can be represented by sum of two squares
    We have number n. We need to find whether number n can be represented by the sum of two squares.Examples : Input : n = 17Output : Yes4^2 + 1^2 = 17Input : n = 169Output : Yes5^2 + 12^2 = 169Input : n = 24Output : NoBrute-force approach - O(n) We use two for loops running till the square root of n an
    15+ min read
    Number of ways of writing N as a sum of 4 squares
    Given a number N, the task is to find the number of ways of writing N as a sum of 4 squares. Two representations are considered different if their terms are in a different order or if the integer being squared (not just the square) is different. Examples: Input : n=1 Output :8 12 + 02 + 02 + 02 02 +
    6 min read
    Count numbers upto N which are both perfect square and perfect cube
    Given a positive integer n, the task is to find the count of numbers from 1 to n which are both perfect squares and cubes.Examples: Input: n = 100Output: 2Explanation: 1 and 64 are the numbers which are both perfect squares (1 and 8) and cubes (1 and 4).Input: n = 100000Output: 6Explanation: 1, 64,
    6 min read
    Sum of all perfect square divisors of numbers from 1 to N
    Given a number N, the task is to find the sum of all the perfect square divisors of numbers from 1 to N. Examples: Input: N = 5 Output: 9 Explanation: N = 5 Perfect square divisors of 1 = 1. Similarly, perfect square divisors of 2, 3 = 1. Perfect square divisors of 4 = 1, 4. Perfect square divisors
    12 min read
    Count of subarrays whose sum is a perfect square
    Given an array arr[] with positive and negative elements, the task is to count all subarrays whose sum is a perfect square. Examples: Input: arr[] = {2, 3, -5, 6, -7, 4}; Output: 5 Explanation: Subarrays {2, 3, -5}, {-5, 6}, {3, -5, 6}, {3, -5, 6, -7, 4} and {4} with sum is 0, 1, 4, 1 and 4 respecti
    10 min read
    Perfect Square factors of a Number
    Given an integer N, the task is to find the number of factors of N which are a perfect square. Examples: Input: N = 100 Output: 4 Explanation: There are four factors of 100 (1, 4, 25, 100) that are perfect square.Input: N = 900 Output: 8 Explanation: There are eight factors of 900 (1, 4, 9, 25, 36,
    10 min read
    Count of primes in a given range that can be expressed as sum of perfect squares
    Given two integers L and R, the task is to find the number of prime numbers in the range [L, R] that can be represented by the sum of two squares of two numbers.Examples: Input: L = 1, R = 5 Output: 1 Explanation: Only prime number that can be expressed as sum of two perfect squares in the given ran
    7 min read
    Count elements in an Array that can be represented as difference of two perfect squares
    Given an array arr[], the task is to count the number of elements in the array that can be represented as in the form of the difference of two perfect square numbers. a^2 - b^2 Examples: Input: arr[] = {1, 2, 3} Output: 2 Explanation: There are two such elements that can be represented as difference
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences