Skip to content
- Tutorials
- Python Tutorial
- Taking Input in Python
- Python Operators
- Python Data Types
- Python Loops and Control Flow
- Python Functions
- Python OOPS Concept
- Python Data Structures
- Python Exception Handling
- Python File Handling
- Python Exercises
- Java
- Java Programming Language
- Java Collections
- Java 8 Tutorial
- Java Programs
- Java Interview Questions
- Java Exercises
- Java Quiz
- Java Projects
- Advance Java
- Programming Languages
- System Design
- Interview Corner
- Computer Science Subjects
- DevOps
- Linux
- Software Testing
- Databases
- Android
- Excel
- Mathematics
- Python Tutorial
- DSA
- Data Structures
- Algorithms
- Analysis of Algorithms
- Searching Algorithms
- Sorting Algorithms
- Greedy Algorithms
- Dynamic Programming
- Graph Algorithms
- Pattern Searching
- Recursion
- Backtracking
- Divide and Conquer
- Mathematical Algorithms
- Geometric Algorithms
- Bitwise Algorithms
- Randomized Algorithms
- Branch and Bound
- Algorithms Tutorial
- DSA Tutorial
- Practice
- All DSA Problems
- Problem of the Day
- Company Wise Coding Practice
- GfG SDE Sheet
- Practice Problems Difficulty Wise
- Language Wise Coding Practice
- Curated DSA Lists
- Competitive Programming
- Company Wise SDE Sheets
- DSA Cheat Sheets
- Top Interview Questions
- Puzzles
- Data Science
- Web Tech
- Courses
-
- DSA Course
- DSA
- Practice Mathematical Algorithm
- Mathematical Algorithms
- Pythagorean Triplet
- Fibonacci Number
- Euclidean Algorithm
- LCM of Array
- GCD of Array
- Binomial Coefficient
- Catalan Numbers
- Sieve of Eratosthenes
- Euler Totient Function
- Modular Exponentiation
- Modular Multiplicative Inverse
- Stein's Algorithm
- Juggler Sequence
- Chinese Remainder Theorem
- Quiz on Fibonacci Numbers
Last Updated : 04 Jan, 2023
Summarize
Comments
Improve
Given a number N, the task is to find the distinct Prime Factors of N.
Examples:
Input: N = 12
Output: 2 3
Explanation: The factors of 12 are 1, 2, 3, 4, 6, 12.
Among these the distinct prime factors are 2 and 3.Input: N = 39
Output: 3 13Approach: The approach is to use a map to check whether a given factor of the number has occurred earlier or not. Now follow the below steps to solve this problem:
- Create a map visited to keep track of all previous prime factors.
- Create a variable C, and initialize it with 2.
- While N is divisible by C, print C if C is not present in the map. Now divide N by C. Also increment C by 1.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using
namespace
std;
// Function to find distinct prime factor
// of a number N
void
distinctPrimeFactors(
int
N)
{
if
(N < 2) {
cout << -1;
}
int
c = 2;
unordered_map<
int
,
bool
> visited;
while
(N > 1) {
if
(N % c == 0) {
if
(!visited) {
cout << c <<
" "
;
visited = 1;
}
N /= c;
}
else
c++;
}
}
// Driver Code
int
main()
{
int
N = 39;
distinctPrimeFactors(N);
return
0;
}
Java
// Java program for the above approach
import
java.util.*;
public
class
GFG
{
// Function to find distinct prime factor
// of a number N
static
void
distinctPrimeFactors(
int
N)
{
if
(N <
2
) {
System.out.print(-
1
);
}
int
c =
2
;
// Create a new dictionary of
// strings, with string keys.
HashMap<Integer, Boolean> visited =
new
HashMap<>();
for
(
int
i =
0
; i < N; i++) {
visited.put(i,
false
);
}
while
(N >
1
) {
if
(N % c ==
0
) {
if
(visited.containsKey(c)){
if
(!visited.get(c)) {
System.out.print(c +
" "
);
visited.put(c,
true
);
}
}
N /= c;
}
else
c++;
}
}
// Driver Code
public
static
void
main(String[] args)
{
int
N =
39
;
distinctPrimeFactors(N);
}
}
// This code is contributed by Samim Hossain Mondal
Python3
# python3 program for the above approach
# Function to find distinct prime factor
# of a number N
def
distinctPrimeFactors(N):
if
(N <
2
):
print
(
-
1
)
c
=
2
visited
=
{}
while
(N >
1
):
if
(N
%
c
=
=
0
):
if
(
not
c
in
visited):
print
(c, end
=
" "
)
See AlsoI am the Smallest Number Having Four Different Prime Factors. Can You Find me??[Solved]Prime Numbers - Definition, Chart, Prime Numbers 1 to 1000, ExamplesWhat are Prime Numbers 1 to 100? Definition, Chart, ExamplesFactors of 120 | Prime Factorization of 120, Factor Tree of 120visited
=
1
if
c
in
visited
else
0
N
/
/
=
c
else
:
c
+
=
1
# Driver Code
if
__name__
=
=
"__main__"
:
N
=
39
distinctPrimeFactors(N)
# This code is contributed by rakeshsahni
C#
// C# program for the above approach
using
System;
using
System.Collections.Generic;
class
GFG
{
// Function to find distinct prime factor
// of a number N
static
void
distinctPrimeFactors(
int
N)
{
if
(N < 2) {
Console.Write(-1);
}
int
c = 2;
// Create a new dictionary of
// strings, with string keys.
Dictionary<
int
,
bool
> visited =
new
Dictionary<
int
,
bool
>();
for
(
int
i = 0; i < N; i++) {
visited[i] =
false
;
}
while
(N > 1) {
if
(N % c == 0) {
if
(visited.ContainsKey(c)){
if
(!visited) {
Console.Write(c +
" "
);
visited =
true
;
}
}
N /= c;
}
else
c++;
}
}
// Driver Code
public
static
void
Main()
{
int
N = 39;
distinctPrimeFactors(N);
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
<script>
// JavaScript program for the above approach
// Function to find distinct prime factor
// of a number N
const distinctPrimeFactors = (N) => {
if
(N < 2) {
document.write(-1);
}
let c = 2;
let visited = {};
while
(N > 1) {
if
(N % c == 0) {
if
(!(c
in
visited)) {
document.write(`${c} `);
visited = 1;
}
N = parseInt(N / c);
}
else
c++;
}
}
// Driver Code
let N = 39;
distinctPrimeFactors(N);
// This code is contributed by rakeshsahni
</script>
Output
3 13
Time Complexity: O(N)
Auxiliary Space: O(N1/2)Efficient Approach: This approach is similar to above approach where we find prime factors. The only difference is that we traverse from 2 to sqrt(n) to find all prime factors since we know that is sufficient for checking for prime numbers as well. If the number is still found to be greater than 2 then it is prime and we need to print it as well.
C++14
// C++ program for the above approach
#include <bits/stdc++.h>
using
namespace
std;
// Function to find distinct prime factor
// of a number N
void
distinctPrimeFactors(
int
N)
{
if
(N < 2) {
cout << -1;
return
;
}
if
(N == 2) {
cout << 2;
return
;
}
unordered_map<
int
,
bool
> visited;
for
(
int
i = 2; i * i <= N; i++) {
while
(N % i == 0) {
if
(!visited[i]) {
cout << i <<
" "
;
visited[i] = 1;
}
N /= i;
}
}
if
(N > 2)
cout << N;
}
// Driver Code
int
main()
{
int
N = 315;
distinctPrimeFactors(N);
return
0;
}
Java
// Java program for the above approach
import
java.util.*;
class
GFG
{
// Function to find distinct prime factor
// of a number N
static
void
distinctPrimeFactors(
int
N)
{
if
(N <
2
) {
System.out.print(-
1
);
return
;
}
if
(N ==
2
) {
System.out.print(
2
);
return
;
}
HashMap<Integer, Boolean> visited =
new
HashMap<>();
for
(
int
i =
2
; i * i <= N; i++) {
while
(N % i ==
0
) {
if
(!visited.containsKey(i)) {
System.out.print(i +
" "
);
visited.put(i,
true
);
}
N /= i;
}
}
if
(N >
2
) {
System.out.print(N);
}
}
// Driver Code
public
static
void
main(String[] args)
{
int
N =
315
;
distinctPrimeFactors(N);
}
}
// This code is contributed by Taranpreet
Python3
# Python program for the above approach
# Function to find distinct prime factor
# of a number N
def
distinctPrimeFactors(N):
if
(N <
2
):
print
(
-
1
)
return
if
N
=
=
2
:
print
(
2
)
return
visited
=
{}
i
=
2
while
(i
*
i <
=
N):
while
(N
%
i
=
=
0
):
if
(i
not
in
visited):
print
(i , end
=
" "
)
visited[i]
=
1
N
/
/
=
i
i
+
=
1
if
(N >
2
):
print
(N)
# Driver Code
N
=
315
distinctPrimeFactors(N);
# This code is contributed by Shubham Singh
C#
// C# program for the above approach
using
System;
using
System.Collections.Generic;
class
GFG
{
// Function to find distinct prime factor
// of a number N
static
void
distinctPrimeFactors(
int
N)
{
if
(N < 2) {
Console.Write(-1);
return
;
}
if
(N == 2) {
Console.Write(2);
return
;
}
Dictionary<
int
,
bool
> visited =
new
Dictionary<
int
,
bool
>();
for
(
int
i = 2; i * i <= N; i++) {
while
(N % i == 0) {
if
(!visited.ContainsKey(i)) {
Console.Write(i +
" "
);
visited[i] =
true
;
}
N /= i;
}
}
if
(N > 2) {
Console.Write(N);
}
}
// Driver code
public
static
void
Main()
{
int
N = 315;
distinctPrimeFactors(N);
}
}
// This code is contributed by avijitmondal1998
Javascript
<script>
// Javascript program for the above approach
// Function to find distinct prime factor
// of a number N
function
distinctPrimeFactors(N)
{
if
(N < 2) {
document.write(-1);
return
;
}
if
(N === 2) {
document.write(2);
return
;
}
visited = {};
for
(
var
i = 2; i * i <= N; i++)
{
while
(N % i == 0)
{
if
(!visited[i])
{
document.write(i +
" "
);
visited[i] = 1;
}
N /= i;
}
}
if
(N > 2)
document.write(N);
}
// Driver Code
var
N = 315;
distinctPrimeFactors(N);
// This code is contributed by Shubham Singh
</script>
Output
3 5 7
Time Complexity: O(N^(1/2))
Auxiliary Space: O(N^(1/2))
Please Login to comment...
Similar Reads
Print all numbers whose set of prime factors is a subset of the set of the prime factors of X
Given a number X and an array of N numbers. The task is to print all the numbers in the array whose set of prime factors is a subset of the set of the prime factors of X. Examples: Input: X = 60, a[] = {2, 5, 10, 7, 17} Output: 2 5 10 Set of prime factors of 60: {2, 3, 5} Set of prime factors of 2: {2} Set of prime factors of 5: {5} Set of prime fa
13 min read
Maximum number of prime factors a number can have with exactly x factors
Given an integer X, denoting the number of factors of a positive integer N can have. The task is to find the maximum number of distinct prime factors the number N can have. Examples: Input: X = 9 Output: 2 Explanation: Some of the possible numbers having 9 factors are: 256: 1, 2, 4, 8, 16, 32, 64, 128, 256 Number of prime factors = 1 36: 1, 2, 3, 4
6 min read
Find prime factors of Z such that Z is product of all even numbers till N that are product of two distinct prime numbers
Given a number N (N > 6), the task is to print the prime factorization of a number Z, where Z is the product of all numbers ≤ N that are even and can be expressed as the product of two distinct prime numbers. Example: Input: N = 6Output: 2→1 3→1Explanation: 6 is the only number ≤ N, which is even and a product of two distinct prime numbers (2 an
7 min read
Count numbers in a given range having prime and non-prime digits at prime and non-prime positions respectively
Given two integers L and R, the task is to find the count of numbers in the range [L, R] having prime digits at prime positions and non-prime digits at non-prime positions. Examples: Input: L = 5, R = 22 Output: 7Explanation: The numbers 6, 8, 9, 12, 13, 15, and 17 have prime digits at prime positions and non-prime digits at non-prime positions. In
15 min read
Number which has the maximum number of distinct prime factors in the range M to N
Given two numbers M and N. The task is to print the number which has the maximum number of distinct prime factors of numbers in range M and N. If there exist multiple numbers, print the smallest one. Examples: Input: a=4, b=10 Output: 6 Number of distinct Prime Factors of 4 is 1 Number of distinct Prime Factors of 5 is 1 Number of distinct Prime Fa
10 min read
Count numbers in a given range whose count of prime factors is a Prime Number
Given a 2D array Q[][] of size N * 2 representing queries of the form {L, R}. For each query, the task is to print the count of numbers in the range [L, R] with a count of prime factors equal to a prime number. Examples: Input: Q[][] = {{4, 8}, {30, 32}} Output: 3 2 Explanation: Query 1: Prime factors of 4 = {2, 2} and count of prime factors = 2 Pr
15 min read
Distinct Prime Factors of Array Product
Given an array of integers. Let us say P is the product of elements of the array. Find the number of distinct prime factors of product P. Examples: Input : 1 2 3 4 5 Output : 3 Explanation: Here P = 1 * 2 * 3 * 4 * 5 = 120. Distinct prime divisors of 120 are 2, 3 and 5. So, the output is 3. Input : 21 30 15 24 16 Output : 4 Explanation: Here P = 21
7 min read
Sort an array according to the increasing count of distinct Prime Factors
Given an array of integers. The task is to sort the given array on the basis of increasing count of distinct prime factors. Examples: Input : arr[] = {30, 2, 1024, 210, 3, 6} Output : 2 1024 3 6 30 210 Input : arr[] = {12, 16, 27, 6} Output : 16 27 6 12 A naive approach is to find all the prime factors of each elements of the array and pair the cou
9 min read
Maximum distinct prime factors of elements in a K-length subarray
Given an array arr[] of N positive integers and an integer K, the task is to find the maximum distinct prime factors in a subarray of length K. Examples: Input: arr[] = {5, 9, 14, 6, 10, 77}, K=3Output: 5Explanation: The sub-array of length 3 with maximum distinct prime factors is 6, 10, 77 and prime factors are 2, 3, 5, 7, 11. Input: arr[] = {4, 2
12 min read
Count ways to split N! into two distinct co-prime factors
Given an integer N, the task is to find the number of ways N! can be split into two distinct factors A and B such that A and B are co-primes. Since the answer can be very large, print it modulo 109 + 7. Examples: Input: N = 5Output: 4Explanation: The pairs are (1, 120), (3, 40), (5, 24), (8, 15). Input: N = 7Output: 8Explanation: The pairs are (1,
10 min read
Maximize sum of count of distinct prime factors of K array elements
Given an array arr[] of size N, the task is to find the maximum sum possible of the count of distinct prime factors of K array elements. Examples: Input: arr[] = {6, 9, 12}, K = 2Output: 4Explanation: Distinct prime factors of 6, 9, 12 are 2, 1, 2. K elements whose distinct prime factors are maximum are 6 and 12. Therefore, sum of their count = 2 +
10 min read
Maximum sum of K-length subarray with maximum count of distinct prime factors
Given an array arr[] consisting of N positive integers and an integer K, the task is to find the maximum sum of array elements in a subarray having maximum sum of distinct prime factors in each K-length subarray. Note: If there are multiple answers then print the sum of the original subarray having maximum sum. Examples: Input: arr[] = {1, 4, 2, 10
11 min read
Count pairs from an array with even product of count of distinct prime factors
Given two arrays A[] and B[] consisting of N and M integers respectively, the task is to count pairs (A[i], B[j]) such that the product of their count of distinct prime factors is even. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 5, 6}, N = 3, M = 3Output: 2Explanation: Replacing all array elements with the count of their distinct prime factors mod
11 min read
Count distinct prime factors for each element of an array
Given an array arr[] of size N, the task is to find the count of distinct prime factors of each element of the given array. Examples: Input: arr[] = {6, 9, 12}Output: 2 1 2Explanation: 6 = 2 × 3. Therefore, count = 29 = 3 × 3. Therefore, count = 112 = 2 × 2 × 3. Therefore, count = 2The count of distinct prime factors of each array element are 2, 1,
15+ min read
Super Ugly Number (Number whose prime factors are in given set)
Super ugly numbers are positive numbers whose all prime factors are in the given prime list. Given a number n, the task is to find the nth Super Ugly number.It may be assumed that a given set of primes is sorted. Also, the first Super Ugly number is 1 by convention. Examples: Input : primes[] = [2, 5] n = 5 Output : 8 Super Ugly numbers with given
14 min read
Number of factors of very large number N modulo M where M is any prime number
Given a large number N, the task is to find the total number of factors of the number N modulo M where M is any prime number. Examples: Input: N = 9699690, M = 17 Output: 1 Explanation: Total Number of factors of 9699690 is 256 and (256 % 17) = 1Input: N = 193748576239475639, M = 9 Output: 8 Explanation: Total Number of factors of 9699690 is 256 an
8 min read
Product of divisors of a number from a given list of its prime factors
Given an array arr[] representing a list of prime factors of a given number, the task is to find the product of divisors of that number. Note: Since the product can be, very large printed, the answer is mod 109 + 7. Examples: Input: arr[] = {2, 2, 3} Output: 1728 Explanation: Product of the given prime factors = 2 * 2 * 3 = 12. Divisors of 12 are {
8 min read
Sum of array elements which are prime factors of a given number
Given an array arr[] of size N and a positive integer K, the task is to find the sum of all array elements which are prime factors of K. Examples: Input: arr[] = {1, 2, 3, 5, 6, 7, 15}, K = 35Output: 12Explanation: From the given array, 5 and 7 are prime factors of 35. Therefore, required sum = 5 + 7 = 12. Input: arr[] = {1, 3, 5, 7}, K = 42Output:
8 min read
Efficient program to print all prime factors of a given number
Given a number n, write an efficient function to print all prime factors of n. For example, if the input number is 12, then the output should be "2 2 3". And if the input number is 315, then the output should be "3 3 5 7". Recommended PracticePrime factorization and geek numberTry It!First Approach:Following are the steps to find all prime factors.
9 min read
Number with maximum number of prime factors
Given an integer N. The task is to find a number that is smaller than or equal to N and has maximum prime factors. In case there are two or more numbers with the same maximum number of prime factors, find the smallest of all.Examples: Input : N = 10Output : 6Number of prime factor of:1 : 02 : 13 : 14 : 15 : 16 : 27 : 18 : 19 : 110 : 26 and 10 have
15+ min read
Count distinct prime triplets up to N such that sum of two primes is equal to the third prime
Given an integer N, the task is to count the number of distinct prime triplets (a, b, c) from the range [1, N] such that a < b < c ? N and a + b = c.Note: Two prime tuples are distinct if at least one of the primes present in them are different. Examples: Input: N = 6Output: 1Explanation: Among numbers in the range [1, 6], the only prime trip
6 min read
Count numbers from a given range having exactly 5 distinct factors
Given two integers L and R, the task is to calculate the count of numbers from the range [L, R] having exactly 5 distinct positive factors. Examples: Input: L = 1, R= 100 Output: 2 Explanation: The only two numbers in the range [1, 100] having exactly 5 distinct factors are 16 and 81. Factors of 16 are {1, 2, 4, 8, 16}. Factors of 81 are {1, 3, 9,
8 min read
Check whether a number has exactly three distinct factors or not
Given a positive integer n(1 <= n <= 1018). Check whether a number has exactly three distinct factors or not. Print "Yes" if it has otherwise "No". Examples : Input : 9Output: YesExplanationNumber 9 has exactly three factors:1, 3, 9, hence answer is 'Yes'Input : 10Output : NoRecommended PracticeThree distinct factorsTry It!Simple approach is
10 min read
Queries to find whether a number has exactly four distinct factors or not
Given a positive integers 'q' and 'n'. For each query 'q' find whether a number 'n' have exactly four distinct divisors or not. If the number have exactly four divisors then print 'Yes' else 'No'.1 <= q, n <= 106 Input: 2 10 12 Output: Yes No Explanation: For 1st query, n = 10 has exactly four divisor i.e., 1, 2, 5, 10. For 2nd query, n = 12
11 min read
Find and Count total factors of co-prime A or B in a given range 1 to N
Given three integers N, A, B, the task is to find the remainder when the sum of integers which are divisible by either A or B in the range [1, N] is divided by the number of integers in this range.Note: The numbers A and B are co-primes. Examples: Input: N = 88, A = 11, B = 8 Output: 8 Explanation: There are a total of 18 numbers in the range [1, 8
12 min read
Maximum Length of Sequence of Sums of prime factors generated by the given operations
Given two integers N and M, the task is to perform the following operations: For every value in the range [N, M], calculate the sum of its prime factors followed by the sum of prime factors of that sum and so on.Generate the above sequence for each array element and calculate the length of the sequence Illustration N = 8 Prime factors = {2, 2, 2}.
12 min read
Print prime factors of a given integer in decreasing order using Stack
Given an integer N, the task is to print prime factors of N in decreasing order using the stack data structure. Examples: Input: N = 34Output:17 2Explanation:The prime factors of the number 34 is 2 and 17. Input: N = 8Output: 2 Approach: The idea is to use the Stack data structure to store all the prime factors of N and in the end, print all the va
4 min read
Sort given Array in descending order according to highest power of prime factors
Given an array arr[] of size N. The task is to sort the elements in arr[] based to their Highest Degree of Expression, in descending order. The Highest Degree of a number is defined as the maximum value in which it can be expressed as the power of its factors. Note: If the numbers have the same degree of expression the element coming first in the o
12 min read
Sum of Factors of a Number using Prime Factorization
Given a number N. The task is to find the sum of all factors of the given number N. Examples: Input : N = 12 Output : 28 All factors of 12 are: 1,2,3,4,6,12 Input : 60 Output : 168 Approach: Suppose N = 1100, the idea is to first find the prime factorization of the given number N. Therefore, the prime factorization of 1100 = 22 * 52 * 11.So, the fo
13 min read
Number less than equals to N with maximum product of prime factors
Given a number N, the task is to find the number which is less than or equals to N whose product of prime factors is maximum.Note: If there is more than one number whose maximum product is equal, then print the smallest number of them.Examples: Input: N = 12 Output: 11 Explanation: Product of prime factor of all numbers before N: 2 = 2 3 = 3 4 = 2
7 min read
Article Tags :
Practice Tags :
Trending in News
- OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
- How to Merge Cells in Google Sheets: Step by Step Guide
- How to Lock Cells in Google Sheets : Step by Step Guide
- PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
- #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank
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
'); $('.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, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('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) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); 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"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `
${comment_text}
`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); 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"); $('.improvement-reason-modal').hide(); } }, }); } 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{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `
${suggest_val}
`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `
Thank You!
Your suggestions are valuable to us.
You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.
`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').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; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { 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(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); 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"); $('.improvement-reason-modal').hide(); } }, }); });