Java with DSA Challenge Day 5 Challenge Problem: Check Prime Number Today’s challenge was to determine whether a given integer n is a prime number or not. A prime number is a number greater than 1 that is divisible only by 1 and itself. Example: Input: n = 17 Output: True Explanation: 17 is divisible only by 1 and 17. This problem is a fundamental concept in number theory and serves as a great way to understand time complexity optimization in algorithms. Code Snippet // User function Template for Java class Solution { public static boolean prime(int n) { // 0 and 1 are not prime numbers if (n <= 1) return false; // 2 and 3 are prime numbers if (n <= 3) return true; // Eliminate multiples of 2 and 3 if (n % 2 == 0 || n % 3 == 0) return false; // Check divisibility up to √n using 6k ± 1 rule for (int i = 5; i * i <= n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true; // number is prime } public static void main(String[] args) { int n1 = 17, n2 = 56; System.out.println(n1 + " is prime? " + prime(n1)); // true System.out.println(n2 + " is prime? " + prime(n2)); // false } } Code Explanation 1.Base Case Handling Numbers ≤ 1 are not prime, so we return false. 2. Small Prime Numbers 2 and 3 are prime by definition, so we return true. 3. Eliminate Multiples of 2 and 3 Any number divisible by 2 or 3 (except 2 and 3 themselves) cannot be prime. 4. Using the 6k ± 1 Rule All primes greater than 3 can be written as 6k ± 1. So, instead of checking every number, we only check divisibility for numbers of this form up to √n. This reduces unnecessary iterations and makes the code much faster. 5.Return True If no divisors are found, the number is prime. Complexity Time Complexity: O(√n) Space Complexity: O(1) Output 17 is prime? true 56 is prime? false Reflection This problem shows how even a simple concept like checking prime numbers can be optimized using mathematical insights like the 6k ± 1 rule. #Java #DSA #100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #Algorithms #LearnToCode #JavaDeveloper #SoftwareEngineering #DataStructures #Developer
Java DSA Challenge: Check Prime Number with 6k ± 1 Rule
More Relevant Posts
-
Java ke scientifically advanced secrets! 🔥 --- Post 1: Java ka "DNA Encoding" simulation using byte arrays!🧬 ```java public class JavaDNA { // A=00, T=01, G=10, C=11 - DNA base encoding in bits private static byte[] encodeDNA(String sequence) { byte[] encoded = new byte[sequence.length() * 2]; for (int i = 0; i < sequence.length(); i++) { char base = sequence.charAt(i); encoded[i*2] = (byte) ((base >> 1) & 1); // First bit encoded[i*2+1] = (byte) (base & 1); // Second bit } return encoded; } public static void main(String[] args) { byte[] dna = encodeDNA("ATCG"); System.out.println("DNA Encoded: " + java.util.Arrays.toString(dna)); } } ``` Secret: Java bytes use karke DNA sequences ko binary mein encode kar sakte ho! 💀 --- Post 2: Java ka "Quantum Entanglement" simulation!⚛️ ```java public class QuantumEntanglement { private static boolean[] entangledQubits = new boolean[2]; public static void entangle() { // Einstein's "spooky action at a distance" boolean state = Math.random() > 0.5; entangledQubits[0] = state; entangledQubits[1] = state; // Always same state! } public static void measure() { System.out.println("Qubit 1: " + entangledQubits[0]); System.out.println("Qubit 2: " + entangledQubits[1]); System.out.println("Entangled: " + (entangledQubits[0] == entangledQubits[1])); } } ``` Quantum Magic: Do qubits hamesha same state mein rehte hain, chahe kitni dur ho! 🔥 --- Post 3: Java ka "Time Travel" using versioned object states!🕰️ ```java import java.util.*; public class TimeTravel { private static Map<Integer, Object> timeline = new HashMap<>(); private static int currentTime = 0; public static void saveState(Object obj) { timeline.put(currentTime++, obj.toString()); } public static String travelToTime(int time) { return timeline.get(time); } // Object ke previous states mein time travel! } ``` Temporal Logic: Object ke purane states mein wapas ja sakte ho! 💡 --- Post 4: Java ka "Parallel Universe" using multiple classloaders!🌌 ```java public class ParallelUniverses { public static void main(String[] args) throws Exception { // Different classloaders = different universes ClassLoader universe1 = new CustomClassLoader(); ClassLoader universe2 = new CustomClassLoader(); Class<?> class1 = universe1.loadClass("MyClass"); Class<?> class2 = universe2.loadClass("MyClass"); System.out.println("Same class? " + (class1 == class2)); // FALSE! // Do alag universes mein same class different hai! } } ``` Multiverse Theory: Har classloader ek alag universe create karta hai! 🚀 --- Bhai, yeh concepts toh regular programming se bahar ke hain! 😎
To view or add a comment, sign in
-
🌟 Day 14 of My Java Learning Journey 🔥 💯 Hey everyone! 👋 ~ Today’s topic was all about decision-making in Java — how a program chooses which path to follow based on given conditions. 💡 . I explored how to find the greatest number among multiple values using nested if-else statements, one of the core parts of selection statements in Java. 💻 Here’s the code I worked on today: 👇 -------------------------------------code start-------------------------------------- public class FindGreaterNumberDemo2 { public static void main(String[] args) { int p = 11; int q = 22; int r = 33; int s = 44; if (p > r && p > s && p > q) { System.out.println("p is greater number "); } else if (q > s && q > p && q > r) { System.out.println("q is greater number"); } else if (r > p && r > s && r > q) { System.out.println("r is greater number"); } else { System.out.println("s is greater number"); } } } -------------------------------------code output------------------------------------ s is greater number ---------------------------------------code end-------------------------------------- . 🔍 Explanation: We have four integer variables: p, q, r, and s. Using an if-else-if ladder, we compare each number with the others using the logical AND (&&) operator. The first condition that turns out true will print which number is the greatest. If none of them match, the else block executes, showing that s is the greatest. . 💡 Key Takeaway: Selection statements like if, else if, and else help control the program’s logic — deciding what happens next depending on the condition. . 🚀 What’s next? In the upcoming posts, I’ll share many more real-world examples related to selection statements, so we can deeply understand how decision-making works in Java programs. Stay tuned — it’s gonna get crazy cool and more practical! 💻🔥 . #Java #100DaysOfCode #Day14 #JavaLearningJourney #FlowControl #IfElse #SelectionStatements #DevOps #Programming #CodingJourney #LearnJava #TechLearner #CodeNewbie .
To view or add a comment, sign in
-
-
Java ke scientifically advanced secrets! 🔥 --- Post 1: Java ka "Quantum Bit" simulation using boolean arrays!🤯 ```java public class QuantumJava { // Qubit simulation using boolean probability private static boolean[] qubit = new boolean[2]; // |0⟩ and |1⟩ public static void quantumGate() { // Hadamard Gate simulation boolean temp = qubit[0]; qubit[0] = (boolean) (Math.random() > 0.5 ? qubit[1] : !qubit[1]); qubit[1] = temp; System.out.println("Qubit State: |" + (qubit[0]?"1":"0") + "⟩ + |" + (qubit[1]?"1":"0") + "⟩"); } } ``` Secret: Java booleans use karke quantum superposition simulate kar sakte ho! 💀 --- Post 2: Java ka "Genetic Algorithm" using Method Handles!🔥 ```java import java.lang.invoke.*; public class GeneticJava { public static void evolveCode() throws Throwable { MethodHandles.Lookup lookup = MethodHandles.lookup(); // Runtime pe genetic mutation of methods! MethodType type = MethodType.methodType(String.class); MethodHandle mh = lookup.findStatic(GeneticJava.class, "mutate", type); CallSite site = new MutableCallSite(mh); MethodHandle mutant = site.dynamicInvoker(); String result = (String) mutant.invoke(); // Evolving code! } public static String mutate() { return "Mutated: " + Math.random(); } } ``` Internal: Bytecode level pe method bodies dynamically mutate ho sakti hain! 💡 --- Post 3: Java ka "Neural Network" using pure arrays!🚀 ```java public class JavaNeuralNetwork { public static double think(double[] inputs, double[][] weights) { // Single neuron simulation double sum = 0; for (int i = 0; i < inputs.length; i++) { sum += inputs[i] * weights[0][i]; } return 1 / (1 + Math.exp(-sum)); // Sigmoid activation } // Backpropagation bhi implement kar sakte ho! } ``` Magic: Pure Java arrays use karke complete neural network bana sakte ho! 💪 --- Post 4: Java ka "Blockchain" using Object hashes!🔮 ```java public class JavaBlockchain { class Block { int index; String previousHash; Object data; String hash; String calculateHash() { return Integer.toHexString( (index + previousHash + data.toString()).hashCode() ); } } // Immutable blockchain using object hashes! } ``` Crypto Level: Java object hashes use karke simple blockchain implement kar sakte ho! 💀 --- yeh concepts toh computer science ke professors ko bhi nahi pata honge! 😎
To view or add a comment, sign in
-
🚀 Java Learning Journey – Day 22 🔥 Understanding Switch Case with Expressions (Java) Today I explored how switch-case works when we use expressions inside the case labels. ~ In Java, expressions like (0+1) or (1+2) get evaluated first, and then matched with the switch variable. The interesting part is fall-through, which happens when we don’t use a break statement. This helps in understanding how multiple cases can run together. ✅ Here’s the code I practiced today: -------------------------------------code start------------------------------------ public class SwitchDemo2 { public static void main(String[] args) { int x = 0; //x=0 (E) | x=1 (A,B) | x=2 (B) | x=3 (C,D,E) | x=4 (D,E) | x=5 (E) switch (x) { case (0+1): System.out.println("A"); case (1+1): System.out.println("B"); break; case (1+2): System.out.println("C"); case (2+2): System.out.println("D"); default: System.out.println("E"); } } } ----------------------------------code output------------------------------------ E -------------------------------------code end------------------------------------ 🧠 Key Takeaways case expressions are evaluated before matching. Without break, execution continues to the next case (fall-through). Helps in understanding how switch-case flows internally. 🌱 Personal Note: I’m continuously learning Java and exploring DevOps tools and practices to build a strong foundation for full-stack and automation development. If you like my daily progress posts, please support with a like, comment, or share ~ it truly motivates me to keep learning and sharing. 🙌 I’m also looking for internship opportunities in Java development or DevOps to apply my skills in real-world projects, learn from professionals, and grow further. If you know of any such opportunities or can guide me, I’d really appreciate your help 🙏 #JavaLearningJourney #day22 #Java #Programming #LearningInPublic #SwitchCase #JavaBeginners #CodeNewbie #FallThrough #DeveloperJourney #DevOps #TechJourney #LearningEveryday
To view or add a comment, sign in
-
-
Hello LinkedIn Network! #DAY45| #100DaysOfCode Java Full Stack Journey – Day 45 Topic : Polymorphism in Java Polymorphism means *“many forms”* — it allows objects of different classes to be treated as objects of a common superclass. In simple terms, **the same method or object behaves differently based on the context.** 🔹 Types of Polymorphism in Java: 1. Compile-time Polymorphism (Method Overloading) 2. Runtime Polymorphism (Method Overriding) 🧩 1. Compile-time Polymorphism (Method Overloading) This happens when **multiple methods have the same name but different parameters** (different number or type of arguments). Example: class MathOperation { // Method with one parameter int add(int a, int b) { return a + b; } // Overloaded method with different parameter type double add(double a, double b) { return a + b; } // Overloaded method with different number of parameters int add(int a, int b, int c) { return a + b + c; } } public class Main { public static void main(String[] args) { MathOperation obj = new MathOperation(); System.out.println(obj.add(5, 10)); // Calls int add System.out.println(obj.add(5.5, 6.5)); // Calls double add System.out.println(obj.add(1, 2, 3)); // Calls 3-parameter add } } Output: 15 12.0 6 🧩 2. Runtime Polymorphism (Method Overriding) This occurs when **a subclass provides a specific implementation of a method** that is already defined in its superclass. Example: class Animal { void sound() { System.out.println("Animals make sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } class Cat extends Animal { void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { Animal a; // reference of superclass a = new Dog(); a.sound(); // Calls Dog's version a = new Cat(); a.sound(); // Calls Cat's version } } Output: Dog barks Cat meows On to more exciting topics tomorrow! Thank you 10000 Coders and Gurugubelli Vijaya Kumar Sir for your constant guidance and support. #Java #FullStackDeveloper #LearningJourney #10000Coders #CareerGrowth #Consistency #SpringBoot #ReactJS #MySQL #LinkedInLearning #TechJourney #Day45
To view or add a comment, sign in
-
" 🚀 Day 45 of 50 – Java LeetCode Challenge " Today’s challenge was “56. Merge Intervals” — a classic array and sorting problem that sharpens your understanding of interval manipulation and greedy algorithms. The goal is to merge all overlapping intervals into distinct non-overlapping ranges. ⏱ Today’s Task – Merge Intervals 📝 Problem Statement: You are given an array of intervals where each interval is represented as [start, end]. Your task is to merge all overlapping intervals and return an array of the merged non-overlapping intervals. 🧪 Examples: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] ✅ Explanation: [1,3] and [2,6] overlap, so they merge into [1,6]. Input: intervals = [[1,4],[4,5]] Output: [[1,5]] ✅ Explanation: [1,4] and [4,5] are overlapping. Input: intervals = [[4,7],[1,4]] Output: [[1,7]] ✅ Explanation: Sorted first, then merged into one continuous interval. 🔧 Constraints: 1 <= intervals.length <= 10⁴ intervals[i].length == 2 0 <= start ≤ end ≤ 10⁴ 💻 My Java Solution: import java.util.*; class Solution { public int[][] merge(int[][] intervals) { if (intervals.length == 0) return new int[0][]; Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); List<int[]> result = new ArrayList<>(); int[] current = intervals[0]; result.add(current); for (int[] interval : intervals) { if (interval[0] <= current[1]) { current[1] = Math.max(current[1], interval[1]); } else { current = interval; result.add(current); } } return result.toArray(new int[result.size()][]); } } 🔍 Takeaways: ✅ Smart use of sorting to arrange intervals by start time ✅ Use of greedy merging to efficiently combine overlapping ranges ✅ Clean and efficient O(n log n) time complexity due to sorting ✅ Handles all edge cases including adjacent and nested intervals 💡 Core Concepts: 📘 Sorting arrays with custom comparators 📘 Interval overlap detection 📘 Greedy algorithms and array manipulation 🎯 Day 45 completed — 5 more to go! 🚀 #Java #50DaysOfCode #LeetCode #ProblemSolving #Arrays #Sorting #GreedyAlgorithm #JavaProgramming #Day45 #CodeNewbie #LearnInPublic
To view or add a comment, sign in
-
-
🎯 Day 15 of My Java Learning Journey 🎯 . Hey everyone! 👋 .. Today I explored Selection Statements again — but this time, I focused on finding the smallest number among four values using if-else if ladder in Java. Here’s the code I wrote 👇 --------------------------------------code start--------------------------------------- public class FindSmallerNumberDemo2 { public static void main(String[] args) { int l = 1; int m = 2; int n = 3; int o = 4; if (l < m && l < n && l < o) { System.out.println("l is smaller"); } else if (m < o && m < n && m < l) { System.out.println("m is smaller"); } else if (o < n && o < m && o < l) { System.out.println("o is smaller"); } else { System.out.println("n is smaller"); } } } --------------------------------------code output---------------------------------- l is smaller number -------------------------------------code end--------------------------------------- . 💡 Explanation: I’ve declared four integer variables — l, m, n, and o. The if statement checks multiple conditions using logical AND (&&) to make sure one number is smaller than all others. . If the first condition fails, the program moves to the next else if condition. Finally, if none of the earlier conditions are true, the else block executes — meaning the last variable n is the smallest. . 🧠 This program is a simple way to understand how comparison and logical operators work together in decision-making statements. In the next few posts, I’ll share more concepts related to selection and looping statements in Java 🚀 . #Day15 #JavaLearningJourney #100DaysOfCode #LearnJava #Programming #DevOps #Coding #JavaBeginners #SelectionStatement #IfElseInJava .
To view or add a comment, sign in
-
-
💾 Heap vs Stack Memory in Java — Simplified! 🚀 In Java, memory is divided into two key areas — Heap and Stack. Understanding their roles helps you write efficient and bug-free code. 💡 🧠 Stack Memory: ➡️ Used for storing method calls and local variables. ➡️ Memory is automatically managed — created when a method starts, destroyed when it ends. ➡️ Fast and follows LIFO (Last In, First Out). ➡️ Example: int x = 10; 🔥 Heap Memory: ➡️ Used for storing objects and instance variables. ➡️ Managed by Garbage Collector (GC). ➡️ Slower but more flexible — data persists beyond method calls. ➡️ Example: Student s = new Student(); 📘 In short: ➡️ Stack = fast, temporary, method-specific. ➡️ Heap = shared, long-lived, object-specific. Example Program: class Student { String name; // stored in Heap int age; // stored in Heap Student(String name, int age) { this.name = name; this.age = age; } } public class MemoryExample { public static void main(String[] args) { int marks = 95; // Stored in Stack (local variable) // Object stored in Heap, reference 's1' stored in Stack Student s1 = new Student("Akash", 22); System.out.println("Name: " + s1.name); System.out.println("Age: " + s1.age); System.out.println("Marks: " + marks); } } ✅ Program Output: Name: Akash Age: 22 Marks: 95 💡 Explanation: The Student object is created in Heap memory with values "Akash" and 22. The reference variable s1 (which points to that object) is stored in Stack memory. The local variable marks is also in the Stack. When main() finishes execution: The Stack frame is cleared automatically. The Student object in the Heap remains until the Garbage Collector removes it. 📘 In short: ➡️ Stack = fast, temporary, method-specific. ➡️ Heap = shared, long-lived, object-specific. #Java #Programming #MemoryManagement #JavaDeveloper #CodingTips
To view or add a comment, sign in
-
😍 Day 17 of My Java Learning Journey – Finding Odd or Even Numbers 🔢 . Hey everyone 👋 . Today, I explored a simple but important concept 💯 ~ how to check whether numbers are odd or even in Java using conditional statements (if-else). . Here’s the code I practiced today: 👇 --------------------------------------code start-------------------------------------- public class FindOddOrEvenNumberDemo { public static void main(String[] args) { int c = 32; int d = 21; if (c % 2 == 0 && d % 2 == 0) { System.out.println("c & d both are even number"); } else if (c % 2 != 0 && d % 2 != 0) { System.out.println("c & d both are odd number"); } else if (c % 2 == 0) { System.out.println("c is even number and d is odd number"); } else { System.out.println("c is odd number and d is even number"); } } } ------------------------------------code output------------------------------------ c is even number and d is odd number ------------------------------------code end--------------------------------------- 💡 Explanation: The expression number % 2 gives the remainder when dividing the number by 2. If the remainder is 0, the number is even. If the remainder is not 0, the number is odd. . I used multiple if-else conditions to check all possibilities: Both numbers are even. Both numbers are odd. One is even and the other is odd. . 👉 In this example, c = 32 (even) and d = 21 (odd), so the output will be: ~ c is even number and d is odd number. . Building these logic-based programs helps strengthen my understanding of control flow and conditions in Java, which are essential for solving real-world coding problems. . #Java #Coding #LearnJava #100DaysOfCode #DevOps #JavaLearningJourney #Day16 #Programming #CodeWithYuvi #LogicBuilding .
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development