Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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
Open In App
Next Article:
Square Free Number
Next article icon

Square Free Number

Last Updated : 05 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a number, check if it is square-free or not. A number is said to be square-free if no prime factor divides it more than once, i.e., the largest power of a prime factor that divides n is one. First few square-free numbers are 1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30, 31, 33, 34, 35, 37, 38, 39, ...
Examples: 

Input: n = 10
Output: Yes
Explanation: 10 can be factorized as 2*5. Since no prime factor appears more than once, it is a square free number.

Input:  n = 20
Output: No
Explanation: 20 can be factorized as 2 * 2 * 5. Since prime factor appears more than once, it is not a square free number. 

The idea is simple, one by one find all prime factors. For every prime factor, we check if its square also divides n. If yes, then we return false. Finally, if we do not find a prime factor that is divisible more than once, we return false.

C++
// C++ Program to print  // all prime factors  # include <bits/stdc++.h> using namespace std;   // Returns true if n is a square free // number, else returns false. bool isSquareFree(int n) {     if (n % 2 == 0)        n = n/2;       // If 2 again divides n, then n is      // not a square free number.     if (n % 2 == 0)        return false;      // n must be odd at this point.  So we can       // skip one element (Note i = i +2)     for (int i = 3; i <= sqrt(n); i = i+2)     {         // Check if i is a prime factor         if (n % i == 0)         {            n = n/i;             // If i again divides, then             // n is not square free            if (n % i == 0)                return false;         }     }      return true; }   // Driver Code int main() {     int n = 10;     if (isSquareFree(n))        cout << "Yes";     else        cout << "No";     return 0; } 
Java
// Java Program to print  // all prime factors  class GFG {          // Returns true if n is a square free     // number, else returns false.     static boolean isSquareFree(int n)     {         if (n % 2 == 0)         n = n / 2;              // If 2 again divides n, then n is          // not a square free number.         if (n % 2 == 0)         return false;              // n must be odd at this point. So we can          // skip one element (Note i = i +2)         for (int i = 3; i <= Math.sqrt(n); i = i + 2)         {             // Check if i is a prime factor             if (n % i == 0)             {                 n = n / i;                          // If i again divides, then                  // n is not square free                 if (n % i == 0)                     return false;             }         }              return true;     }          /* Driver program to test above function */     public static void main(String[] args)     {         int n = 10;         if (isSquareFree(n))             System.out.println("Yes");         else             System.out.println("No");     } }  // This code is contributed by prerna saini. 
Python3
# Python3 Program to print  # all prime factors from math import sqrt  # Returns true if n is # a square free number,  # else returns false. def isSquareFree(n):          if n % 2 == 0:         n = n / 2      # If 2 again divides n,      # then n is not a square     # free number.     if n % 2 == 0:         return False      # n must be odd at this     # point. So we can skip     # one element      # (Note i = i + 2)     for i in range(3, int(sqrt(n) + 1)):                  # Check if i is a prime         # factor         if n % i == 0:             n = n / i          # If i again divides, then          # n is not square free         if n % i == 0:             return False     return True  # Driver program n = 10  if isSquareFree(n):     print ("Yes") else:     print ("No")      # This code is contributed by Shreyanshi Arun. 
C#
// C# Program to print  // all prime factors using System;  class GFG {          // Returns true if n is a square free     // number, else returns false.     static bool isSquareFree(int n)     {         if (n % 2 == 0)         n = n / 2;              // If 2 again divides n, then n is          // not a square free number.         if (n % 2 == 0)         return false;              // n must be odd at this point. So we can          // skip one element (Note i = i +2)         for (int i = 3; i <= Math.Sqrt(n); i = i + 2)         {             // Check if i is a prime factor             if (n % i == 0)             {                 n = n / i;                          // If i again divides, then                  // n is not square free                 if (n % i == 0)                     return false;             }         }              return true;     }          // Driver program      public static void Main()     {         int n = 10;         if (isSquareFree(n))         Console.WriteLine("Yes");         else             Console.WriteLine("No");     } }  // This code is contributed by vt_m. 
PHP
<?php // PHP Program to print  // all prime factors  // Returns true if n is a square free // number, else returns false. function isSquareFree($n) {     if ($n % 2 == 0)         $n = $n / 2;      // If 2 again divides n, then n is      // not a square free number.     if ($n % 2 == 0)         return false;      // n must be odd at this     // point. So we can skip       // one element (Note i = i +2)     for ($i = 3; $i <= sqrt($n);                     $i = $i + 2)     {                  // Check if i is a prime factor         if ($n % $i == 0)         {             $n = $n / $i;                  // If i again divides, then              // n is not square free             if ($n % $i == 0)                 return false;         }     }      return true; }  // Driver Code $n = 10; if (isSquareFree($n))     echo("Yes"); else     echo("No");  // This code is contributed by Ajit. ?> 
JavaScript
<script>  // JavaScript Program to print  // all prime factors      // Returns true if n is a square free     // number, else returns false.     function isSquareFree(n)     {         if (n % 2 == 0)         n = n / 2;                // If 2 again divides n, then n is          // not a square free number.         if (n % 2 == 0)         return false;                // n must be odd at this point. So we can          // skip one element (Note i = i +2)         for (let i = 3; i <= Math.sqrt(n); i = i + 2)         {             // Check if i is a prime factor             if (n % i == 0)             {                 n = n / i;                            // If i again divides, then                  // n is not square free                 if (n % i == 0)                     return false;             }         }                return true;     }   // Driver code                 let n = 10;         if (isSquareFree(n))             document.write("Yes");         else             document.write("No");        </script> 

Output
Yes

Time Complexity: O(sqrt(N)), In the worst case when the number is a perfect square, then there will be sqrt(n)/2 iterations.
Auxiliary Space: O(1)


Next Article
Square Free Number

S

Shashank_Pathak
Improve
Article Tags :
  • Mathematical
  • Competitive Programming
  • DSA
  • prime-factor
  • divisors
Practice Tags :
  • Mathematical

Similar Reads

    Special two digit number
    A special two-digit number is a number such that when the sum of the digits of the number is added to the product of its digits, the result is equal to the original two-digit number. Examples : input : 59. output : 59 is a Special Two-Digit Number Explanation: Sum of digits = 5 + 9 = 14 Product of i
    6 min read
    Mathematical Algorithms - Number Digits
    "Mathematical Algorithms | Number Digits" is a guide that explores problems and solutions involving digits. It covers common digit-related issues, such as digit properties, manipulation, and counting under constraints. The article discusses algorithmic approaches like modular arithmetic, string hand
    9 min read
    POTD Solutions | 10 Nov’ 23 | Number following a pattern
    Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Stack and Two Pointer Algorithm but will also help you build up problem-solving
    6 min read
    What is the smallest 3 digit number with unique digits?
    In our daily lives, we use numbers. They are frequently referred to as numerals. We can’t count objects, date, time, money, or anything else without numbers. These numerals are sometimes used for measurement and other times for labeling. Numbers have features that allow them to conduct arithmetic op
    5 min read
    Is negative 12 a whole number?
    Numerals are the mathematical figures used in financial, professional as well as a social field in the social world. The digits and place value in the number and the base of the number system determine the value of a number. Numbers are used in various mathematical operations as summation, subtracti
    4 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.

What kind of Experience do you want to share?

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