Showing posts with label hackerrank. Show all posts
Showing posts with label hackerrank. Show all posts

Tuesday, 8 November 2016

Hackerrank , Project Euler #5: Smallest multiple

Project Euler #5: Smallest multiple


from fractions import gcd
def lcm(numbers):
    return reduce(lambda x, y: (x*y)/gcd(x,y), numbers)
t=input()
for i in range(0,t):
    print lcm(range(1,input()+1))

Hackerrank , Project Euler #4: Largest palindrome product

Project Euler #4: Largest palindrome product


# Enter your code here. Read input from STDIN. Print output to STDOUT
t=input()
for i in range(0,t):
    no=input()
    for k in range(no-1,101100,-1):
        if str(k)==str(k)[::-1]:
            lst = [k for e in range(100,999) if k%e==0 and len(str(k/e))==3]
            if lst :
                print max(lst)
                break

Hckerrank , Project Euler #3: Largest prime factor

Project Euler #3: Largest prime factor


# Enter your code here. Read input from STDIN. Print output to STDOUT
t=input()
def largest_prime_factor(n):
    i = 2
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
    return n

for j in range(0,t):
    n=input()
    print largest_prime_factor(n)

Thursday, 14 July 2016

Hackerrank , Project Euler #1: Multiples of 3 and 5

Here you can find solutions for  the famous Euler Project's Problems . Questions can find on following link https://www.hackerrank.com/contests/projecteuler/challenges.

 Project Euler #1: Multiples of 3 and 5     :

# Enter your code here. Read input from STDIN. Print output to STDOUT
t= input()
for i in range(0,t):
    no=input()
    n=(no-1)/3
    sum_3=(n*(2*3+3*(n-1))/2)
    n=(no-1)/5
    sum_5=(n*(2*5+5*(n-1))/2)
    n=(no-1)/15
    sum_15=(n*(2*15+15*(n-1))/2)
    print sum_3+sum_5-sum_15

Wednesday, 6 July 2016

Hackerrank , 30 Days of Code Challenges ( Day 28 & 29 Solution)

Day 28: RegEx, Patterns, and Intro to Databases  :

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        for(int a0 = 0; a0 < N; a0++){
            String firstName = in.next();
            String emailID = in.next();
        }
    }
}

Day 29: Bitwise AND  :

import java.util.Scanner;
public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int T = sc.nextInt();
        for (int tc = 0; tc < T; tc++) {
            int N = sc.nextInt();
            int K = sc.nextInt();

            System.out.println(solve(N, K));
        }

        sc.close();
    }

    static int solve(int N, int K) {
        int result = 0;
        for (int A = 1; A <= N; A++) {
            for (int B = A + 1; B <= N; B++) {
                int current = A & B;
                if (current > result && current < K) {
                    result = current;
                }
            }
        }
        return result;
    }
}

Hackerrank , 30 Days of Code Challenges ( Day 26th & 27th Solution)

 Day 26: Nested Logic :
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int actualDay = sc.nextInt();
        int actualMonth = sc.nextInt();
        int actualYear = sc.nextInt();
        int expectedDay = sc.nextInt();
        int expectedMonth = sc.nextInt();
        int expectedYear = sc.nextInt();

        int fine;
        if (actualYear > expectedYear) {
            fine = 10000;
        } else if (actualMonth > expectedMonth && (actualYear >= expectedYear)) {
            fine = 500 * (actualMonth - expectedMonth);
        } else if (actualDay > expectedDay && (actualMonth >= expectedMonth) && (actualYear >= expectedYear)) {
            fine = 15 * (actualDay - expectedDay);
        } else {
            fine = 0;
        }
        System.out.println(fine);

        sc.close();
    }
}

Day 27: Testing :

print "5"
print "4 3"
print "-1 0 4 2"
print "5 3"
print "0 1 -2 -6 9"
print "6 4"
print "1 0 -3 4 5 7"
print "7 5"
print "0 -3 -2 -1 6 -8 9"
print "8 6"
print "2 -4 5 1 3 7 6 0"

Hackerrank , 30 Days of Code Challenges ( Day 24 & 25 Solutions)

Day 24: More Linked Lists   :

public static Node removeDuplicates(Node head) {
     //Write your code here
       Node currentNode = head;
       while(currentNode!=null && currentNode.next!=null)
           {
           Node node = currentNode;
           while(node.next!=null)
               {
               if(node.next.data==currentNode.data)
                   {
                   Node next = node.next.next;
                   Node temp= node.next;
                   node.next=next;
                   temp=null;

               }
               else{
               node=node.next;
               }
           }
           currentNode=currentNode.next;
       }
       return head;
   }

Day 25: Running Time and Complexity  :

# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
t=input()
def isPrime(data):
    if data < 2:
        return False
    v=int(math.sqrt(data))
    for i in range(2,v+1):
        if data%i==0:
            return False;
    return True;
for i in range(t):
    if isPrime(input()):
        print "Prime"
    else:
        print "Not prime"

   

Hackerrank , 30 Days of Code Challenges ( Day 21 - 23 Solutions)

Day 21: Generics  :
//Write your code here

static <E>  void printArray( E[] inputArray)
{
for( E e : inputArray)
    {
    System.out.println(""+e);
}

}

Day 22: Binary Search Trees  :

public static int getHeight(Node root){
    //Write your code here
      if(root ==null)
          return -1;
      int left=getHeight(root.left);
      int right=getHeight(root.right);
      return Math.max(left, right) + 1;
  }

Day 23: BST Level-Order Traversal   :

    static void levelOrder(Node root){
      //Write your code here
        Queue<Node> queue = new LinkedList<Node>();
        queue.add(root);
        while(queue.peek()!=null)
            {
            Node node =queue.remove();
            System.out.print(""+node.data+" ");
            if(node.left!=null)
                queue.add(node.left);
            if(node.right!=null)
                queue.add(node.right);
        }
    }

Wednesday, 29 June 2016

Hackerrank , 30 Days of Code Challenges ( Day 19 Solution)


 Day 19: Interfaces   :


//Write your code here
class Calculator implements AdvancedArithmetic
    {

    public int divisorSum(int n)
        {
        int sum=0;
        for(int i=1 ; i<=n;i++)
            {
            if(n%i==0)
                sum+=i;
        }
        return sum;
    }
}

Hackerrank , 30 Days of Code Challenges ( Day 20 Solution)

Day 20: Sorting   :

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int a[] = new int[n];
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }


         int numberOfSwaps=0;
        for (int i = 0; i < n; i++) {

            for (int j = 0; j < n - 1; j++) {
                 if (a[j] > a[j + 1]) {
                   int temp=a[j];
                    a[j]=a[j+1];
                    a[j+1]=temp;
                    numberOfSwaps++;
                }
            }
            if (numberOfSwaps == 0) {
                break;
            }
        }

        System.out.println("Array is sorted in "+numberOfSwaps+" swaps.");
        System.out.println("First Element: "+a[0]);
        System.out.println("Last Element: "+a[a.length-1]);
    }


}

Tuesday, 28 June 2016

Hackerrank , 30 Days of Code Challenges ( Day 18 Solution)

 Day 18: Queues and Stacks   :

public class Solution {
    // Write your code here.
    Stack<Character> stack = new Stack<Character>();
    Queue<Character> queue = new LinkedList<Character>();
    void pushCharacter(char ch)
        {
        stack.push(ch);
    }
     void enqueueCharacter(char ch){
        queue.add(ch);
     }
    char popCharacter() {
        return stack.pop();
    }

    char dequeueCharacter()
        {
        return queue.remove();
    }

Hackerrank , 30 Days of Code Challenges ( Day 16 & Day 17 Solutions)

Day 16: Exceptions - String to Integer    :
 import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        try{
        String S = in.next();
            System.out.println(""+Integer.parseInt(S));
    }catch(Exception e)
            {
            System.out.println("Bad String");
        }
    }
}

Day 17: More Exceptions   :
class Calculator :
    def power(self, a, b):
        if a>= 0 and b>=0:
            return a**b
        else:
            return "n and p should be non-negative"
 

Hackerrank , 30 Days of Code Challenges ( Day 13 - 15 Solutions)

Day 13: Abstract Classes   :
 
//Write MyBook Class
class MyBook extends Book
    {
    int price;
    MyBook(String t , String a , int p)
        {
        super(t,a);
        this.price =p;
    }
    void display()
        {
        System.out.println("Title: "+title);
        System.out.println("Author: "+author);
        System.out.println("Price: "+price);
    }
}

Day 14: Scope   :

    # Add your code here
    def computeDifference(self):
        self.maximumDifference =  max(a)-min(a)


Day 15: Linked List   :
 class MyBook extends Book
    {
    int price;
    MyBook(String t , String a , int p)
        {
        super(t,a);
        this.price =p;
    }
    void display()
        {
        System.out.println("Title: "+title);
        System.out.println("Author: "+author);
        System.out.println("Price: "+price);
    }
}

Hackerrank , 30 Days of Code Challenges ( Day 12 Solution)

 Day 12: Inheritance    :

class Student extends Person{
    private int[] testScores;
    Student(String firstName, String lastName, int identification , int [] scores)
        {
        super(firstName,lastName,identification );
        this.testScores=scores;
    }

    public String calculate()
        {
        int sum =0;
        for(int i : this.testScores)
            {
            sum+=i;
        }
        double avg= sum/testScores.length;
        if (avg<=100 && avg>=90)
            {
            return "O";
        }else if(avg<90 && avg>=80)
            {
             return "E";
        }
        else if(avg<80 && avg>=70)
            {
             return "A";
        }
        else if(avg<70 && avg>=55)
            {
             return "P";
        }
         else if(avg<55 && avg>=40)
            {
             return "D";
        }
        else{
             return "T";
        }
    }

}

Hackerrank , 30 Days of Code Challenges ( Day 10 & Day 11 Solutions)

Day 10: Binary Numbers    :

import sys
n = int(raw_input().strip())
string = '{0:b}'.format(n)
array=string.split('0')
array.sort()
print len(array[len(array)-1])

Day 11: 2D-Arrays    :
arr = []
max=-999
for arr_i in xrange(6):
   arr_temp = map(int,raw_input().strip().split(' '))
   arr.append(arr_temp)

for i in xrange(4):
    for j in xrange(4):
        temp=arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]
    if temp > max:
        max=temp

print max

Friday, 24 June 2016

Hackerrank , 30 Days of Code Challenges ( Day 6-9 Solutions)

Day 6: Let's Review  :
# Enter your code here. Read input from STDIN. Print output to STDOUT
t=input()
for i in range(0,t):
    string =raw_input()
    print ''.join([string[i] for i in range(0,len(string),2)])+" "+''.join([string[i] for i in range(1,len(string),2)])

Day 7: Arrays   :
#!/bin/python
import sys
n = int(raw_input().strip())
arr = map(int,raw_input().strip().split(' '))
arr.reverse()
print " ".join(str(i) for i in arr)

Day 8: Dictionaries and Maps     :
# Enter your code here. Read input from STDIN. Print output to STDOUT
t=input()
data=dict()
index=[]
for i in range(0,t):
    array=raw_input().split(" ")
    data[array[0]]=array[1]
for k in range(0,t):
    inp= raw_input()
    if data.has_key(inp):
        print inp+"="+data[inp]
    else:
        print "Not found"

Day 9: Recursion    :
n= input()
def factorial(n):
    if n ==0 or n==1 :
        return 1
    else:
        return n*factorial(n-1)
print factorial(n)





Saturday, 18 June 2016

Hackerrank , 30 Days of Code Challenges ( Day 0-5 Solutions)

Hackerrank , 30 Days of Code Challenges  =>

Day 0: Hello, World (Python) :

inputString = raw_input() # get a line of input from stdin and save it to our variable

# Your first line of output goes here
print 'Hello, World.'

# Write the second line of output
print inputString

Day 1: Data Types (C#) :

// Declare second integer, double, and String variables.
        int i2;
        double d2;
        string s2;
       
        // Read and save an integer, double, and String to your variables.
        i2=int.Parse(Console.ReadLine());
        d2= double.Parse(Console.ReadLine());
        s2 = Console.ReadLine();
       
        // Print the sum of both integer variables on a new line.
        Console.WriteLine("{0:#.#}",i2+i);
       
        // Print the sum of the double variables on a new line.
        Console.WriteLine("{0:0.0}",d+d2);
        // Concatenate and print the String variables on a new line
        // The 's' variable above should be printed first.
        Console.WriteLine(s+s2);

Day 2: Operators (Python) :

a=raw_input()
b=raw_input()
c=raw_input()
print "The total meal cost is "+str(int(round(float(a)+(float(b)*float(a)/100)+(float(c)*float(a)/100))))+" dollars."


Day 3: Intro to Conditional Statements (Python) :

 #!/bin/python

import sys


N = int(raw_input().strip())

if N%2!=0:
    print "Weird"
elif N>=2 and N<=5 :
    print "Not Weird"
elif N>=6 and N<=20 :
    print "Weird"
else:
    print "Not Weird"
    

Day 4: Class vs. Instance (Java) :

public class Person {
    private int age;   
 
    public Person(int initialAge) {
          // Add some more code to run some checks on initialAge
        this.age=initialAge;
    }

    public void amIOld() {
          // Write code determining if this person's age is old and print the correct statement:
        if(this.age<0)
          { System.out.println("Age is not valid, setting age to 0.");
           this.age=0;
           amIOld();
          }
        else if(this.age<13)
            System.out.println("You are young.");
        else if(this.age<18)
            System.out.println("You are a teenager.");
        else if(this.age>=18)
            System.out.println("You are old.");
    }

    public void yearPasses() {
          // Increment this person's age.
        this.age+=1;
    }

Day 5: Loops (Python) :

#!/bin/python

import sys


N = int(raw_input().strip())
for i in xrange(1,11):
    print str(N)+" x "+str(i)+" = "+str(N*i)