CseWay

A Way For Learning

Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Fibonacci-Prime Number


Fibonacci-prime number : Given a number N, you need to find if N is fibonacci-prime number or not. A fibonacci-prime is any number that is both a prime and a fibonacci number.

import java.math.BigInteger;
import java.util.HashSet;
import java.util.Scanner;

public class Solution
{
    static boolean isPrime(BigInteger bigInteger)
    {
        if(bigInteger.isProbablePrime(1))
            return true;
        return false;
    }

    @SuppressWarnings("unchecked")
    static void findAndSetFibonacciPrimeNumbers(HashSet set)
    {
        BigInteger a=new BigInteger("0");
        BigInteger b=new BigInteger("1");
        BigInteger s=a.add(b);
        BigInteger range=new BigInteger("10").pow(75);
        while (range.compareTo(s)==1)
        {
            a=b;
            b=s;
            s=a.add(b);
            if(s.isProbablePrime(2))
                set.add(s);
        }
    }
    public static void main(String[] args)
    {
        HashSet<BigInteger> set=new HashSet<>();
        findAndSetFibonacciPrimeNumbers(set);
        /*System.out.println(set.toString());*/
        Scanner sc=new Scanner(System.in);
        int testCases=sc.nextInt();
        while (testCases-->0)
        {
            BigInteger n=new BigInteger(sc.next());
            if(set.contains(n))
                System.out.println(1);
            else System.out.println(0);
        }
    }
}

Monotone Increasing Digits

Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.
(An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.)
Examples :
Input: N = 10
Output: 9
Input: N = 1234
Output: 1234
Input: N = 332
Output: 299

import java.util.*;
class Solution {
    public static int monotoneIncreasingDigits(int N) {
        String S = String.valueOf(N);
        String ans = "";
        search: for (int i = 0; i < S.length(); ++i) {
            for (char d = '1'; d <= '9'; ++d) {
                if (S.compareTo(ans + repeat(d, S.length() - i)) < 0) {
                    ans += (char) (d - 1);
                    continue search;
                }
            }
            ans += '9';
        }
        return Integer.parseInt(ans);
    }

    public static String repeat(char c, int count) {
        StringBuilder sb = new StringBuilder(count);
        for (int i = 0; i < count; ++i) sb.append(c);
        return sb.toString();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = Integer.parseInt(sc.nextLine());
        int output = monotoneIncreasingDigits(num);
        System.out.print(output);
    }
}

Sort based on frequency of characters

Given a string, sort it in decreasing order based on the frequency of characters.
Input: "tree"
Output:"eert"
Explanation:
'e' appears twice while 'r' and 't' both appear once.

 So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

import java.util.*;

class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        String output=frequencySort(input);
        System.out.println(output);
    }
    

public static String frequencySort(String s) {
        int[][] count = new int[256][2];
        
        for(char c: s.toCharArray()) {
            count[c][0] = c;
            count[c][1]++;
        }
        
        Arrays.sort(count, new Comparator<int[]>() {
           public int compare(int[] a, int[] b) {
               return a[1] == b[1] ? 0 : (a[1] < b[1] ? 1 : -1);
           } 
        });
        
        
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<256; i++) {
            if (count[i][1] > 0) {
                for(int j=0; j<count[i][1]; j++) {
                    sb.append((char)count[i][0]);
                }
            }
        }
        
        return sb.toString();
    }
}

Missing Positive Integer

Find the smallest positive number missing from an unsorted array .
Examples
Input: {2, 3, 7, 6, 8, -1, -10, 15}
Output: 1
Input: { 2, 3, -7, 6, 8, 1, -10, 15 }
Output: 4
Input: {1, 1, 0, -1, -2}
Output: 2  

// java program to find maximum
// element

import java.util.*;

class Solution
/* Utility function that puts all non-positive 
(0 and negative) numbers on left side of 
arr[] and return count of such numbers */
static int segregate (int arr[], int size)
{
int j = 0, i;
for(i = 0; i < size; i++)
{
if (arr[i] <= 0) 
{
int temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
// increment count of non-positive 
// integers
j++; 
}
}
return j;
}
/* Find the smallest positive missing 
number in an array that contains
all positive integers */
static int findMissingPositive(int arr[], int size)
{
int i;
// Mark arr[i] as visited by making 
// arr[arr[i] - 1] negative. Note that 
// 1 is subtracted because index start 
// from 0 and positive numbers start from 1
for(i = 0; i < size; i++)
{
if(Math.abs(arr[i]) - 1 < size && arr[Math.abs(arr[i]) - 1] > 0)
arr[Math.abs(arr[i]) - 1] = -arr[Math.abs(arr[i]) - 1];
}
// Return the first index value at which 
// is positive
for(i = 0; i < size; i++)
if (arr[i] > 0)
return i+1; // 1 is added becuase indexes 
// start from 0
return size+1;
}
/* Find the smallest positive missing 
number in an array that contains
both positive and negative integers */
static int findMissing(int arr[], int size)
{
// First separate positive and 
// negative numbers
int shift = segregate (arr, size);
int arr2[] = new int[size-shift];
int j=0;
for(int i=shift;i<size;i++)
{
arr2[j] = arr[i];
j++;
// Shift the array and call 
// findMissingPositive for
// positive part
return findMissingPositive(arr2, j);
}
// main function
public static void main (String[] args) 
{
Scanner sc= new Scanner(System.in);
int numInputs = Integer.parseInt(sc.nextLine());
if(numInputs>0){
int arra[] = new int[numInputs];
for (int i=0;i<numInputs ;i++ ) {
arra[i]= Integer.parseInt(sc.nextLine());
}
// int arr[] = {0, 10, 2, -10, -20};
// int arr_size = arr.length;

//int missing = findMissing(arr, arr_size);
int missing = findMissing(arra,numInputs);
System.out.println(missing);
}
}
}

Count Digits that doesn't contain 3

  1. Given a number n, write a function that returns count of numbers from 1 to n that don’t contain digit 3 in their decimal representation.
Examples:
Input: n = 10
Output: 9
Input: n = 45
Output: 31

Numbers 3, 13, 23, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43 contain digit 3. 

// Java program to count numbers that not contain 3
import java.io.*;
import java.util.*;

class Solution
{
    // Function that returns count of numbers which 
    // are in range from 1 to n 
    // and not contain 3 as a digit
    static int count(int n)
    {
        // Base cases (Assuming n is not negative)
        if (n < 3)
            return n;
        if (n >= 3 && n < 10)
            return n-1;

        // Calculate 10^(d-1) (10 raise to the power d-1) where d is
        // number of digits in n. po will be 100 for n = 578
        int po = 1;
        while (n/po > 9)
            po = po*10;

        // find the most significant digit (msd is 5 for 578)
        int msd = n/po;

        if (msd != 3)
            // For 578, total will be 4*count(10^2 - 1) + 4 + count(78)
            return count(msd)*count(po - 1) + count(msd) + count(n%po);
        else
            // For 35, total will be equal to count(29)
            return count(msd*po - 1);
    }
    
    // Driver program
    public static void main (String[] args) 
    {
        int n = 578;
        Scanner sc = new Scanner(System.in);
        int m = Integer.parseInt(sc.nextLine());
        if(m>=0){
        System.out.println(count(m));
    }
    }
}


Validating ISBN

Validating ISBN: Write a C program to define a structure Book with the attributes, book title,
author, subject, isbn number, Based on the given input values display the books information if the
given ISBN is valid.
Following are the rules to verify whether the given ISBN is a valid or not.
The 2001 edition of the official manual of the International ISBN Agency says that the ISBN-10
check digit – which is the last digit of the ten-digit ISBN – must range from 0 to 10 (the symbol X is
used for 10), and must be such that the sum of all the ten digits, each multiplied by its (integer)
weight, descending from 10 to 1, is a multiple of 11.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

_Bool isValidISBN(long);
int getLength(char*);

int main(int argc, char *argv[]) {
 struct Book {
  char *bookTitle;
  char *bookAuthor;
  char *subject;
  long isbn;
 };

 struct Book book[5];
 int n;
 char *s = (char *)malloc(sizeof(char)*100);
 int length = getLength(s);
 scanf("%d", &n);
 for(int i=0; i<n; i++) {
  scanf("%s", s);
  fflush(stdin);
  int length = getLength(s);
  book[i].bookTitle = (char *)malloc(sizeof(char) * length);
  strcpy(book[i].bookTitle, s);
  scanf("%s", s);
  fflush(stdin);
  length = getLength(s);
  book[i].bookAuthor = (char *)malloc(sizeof(char) * length);
  strcpy(book[i].bookAuthor, s);
  scanf("%s", s);
  length = getLength(s);
  fflush(stdin);
  book[i].subject = (char *)malloc(sizeof(char) * length);
  strcpy(book[i].subject, s);
  scanf("%ld", &book[i].isbn);
  if(isValidISBN(book[i].isbn)==true) {
   printf("{Book Title : %s; ", book[i].bookTitle);
   printf("Book Author : %s; ", book[i].bookAuthor);
   printf("Subject : %s; ", book[i].subject);
   printf("ISBN : %ld}\n", book[i].isbn);
  }
 }
}

int getLength(char *s) {
 int length = 0;
 while(s[length]!='\0') {
  length++;
 }
 return length;
}

_Bool isValidISBN(long isbn) {
 long sum = 0;
 int i = 1;
 while(isbn>0) {
  sum = sum + (isbn)%10 * i;
  isbn = isbn / 10;
  i++;
 }
 if(sum%11==0)
  return true;
 return false;
}

Project Euler #7: 10001st prime

By listing the first six prime numbers: and , we can see that the prime is .
What is the prime number?

a = [0]*200008
for i in range(2,200000):
    if (a[i] == 1):
        continue
    for j in range(2*i,200000,i):
        a[j] = 1
primes = []
for i in range(2,200000):
    if a[i] == 0:
        primes.append(i)
p = int(input())
for _ in range(p):
 t = int(input())
 print(primes[t-1])

Sum of Factorials of the digits of N.

Sum of Factorial of the digits of the given number: Write a python program to compute sum of
the factorials of each digit of a given integer. Write a separate function for calculating the
factorial of a number.

def fact(n):
    result = 1
    for i in range(n):
        result *= i + 1
    return result

def sum_of_fact(n):
    result = 0
    if(n <= 0):
     return 1
    else:
     while n > 0:
         result += fact(n % 10)
         n = n // 10
     return result

print(sum_of_fact(int(input())))

import java.util.Scanner;

public class Solution {

 public static long factorialN(long n) {
  if (n <= 0)
   return 1;
  else 
   return n * factorialN(n-1);
 }

 public static void main(String[] args) {
  Scanner scan = new Scanner(System.in);
  long n = scan.nextLong();
  int sum = 0;
  if(n <= 0) {
   System.out.println("1");
  } else {
   while(n != 0) {
    sum = sum + (int)factorialN(n%10);
    n = n/10;
   }
   System.out.println(sum);
  }
 }
}

C
#include <stdio.h>

long long int factorialN(long long int n) {
 if (n <= 0)
  return 1;
 else 
  return n * factorialN(n-1); 
}

int main(int argc, char const *argv[]) {
 long long int n = 0;
 long long int sum = 0;
 scanf("%llu",&n);
 if(n <= 0) {
  printf("1");
 } else {
  while(n != 0) {
   sum = sum + factorialN(n%10);
   n = n/10;
  }
  printf("%llu\n",sum);
 }
 return 0;
}

Moving all Zeros to the Left Side of the Array

Moving all Zeros to the Left Side of the Array: Write a program to move all the zeros on the
left side of the array while maintaining the relative order of non-zero elements. You should not
use another array.

Solution :
C
/*
    Float all zeros to the left of an array
*/

#include <stdio.h>
#include <stdlib.h>

void float_zeros(int *arr, int len);
void print_array(int *arr, int len);

int main(void) {
    int n = 0, *arr = NULL, i = 0;
    scanf("%d", &n);

    if(n <= 0) {
        fprintf(stderr, "The array size can't be zero or negative\n");
        return 1;
    }

    arr = (int*)calloc(1, n * sizeof(int));
    for(i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    float_zeros(arr, n);
    print_array(arr, n);

    free(arr);
    return 0;
}

void float_zeros(int *arr, int len) {
    /*
        Find all the 0s in arr, and float them to the left end of arr.
    */
    int i = 0, prev = 0, j = 0, k = 0, temp = 0;
    while(i < len) {
        // Find zeros
        if(*(arr + i) == 0) {
            // Found a zero. Now float it.
            // To do that, we need where to float it to.
            // That would be prev.
            for(j = i; j > prev; j--) {
                k = j - 1;
                temp = *(arr + j);
                *(arr + j) = *(arr + k);
                *(arr + k) = temp;
            }
            prev++;
        }
        i++;
    }
}

void print_array(int *arr, int len) {
    /*
        Prints an int array of length len
    */

    int i = 0;
    while(i < len) {
        printf("%d", *(arr + i));
        if(i != len - 1)
            printf(" ");
        i++;
    }
    printf("\n");
}


JAVA:

/*
    Float zeros
*/

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        int n = 0;

        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();

        if(n <= 0)
            System.err.println("The array size can't be zero or negative");

        int arr[] = new int[n];
        for(int i = 0; i < n; i++)
            arr[i] = sc.nextInt();

        sc.close();

        // Changing the array elements here.
        int i = 0, prev = 0;
        while(i < n) {
            // Find a zero
            if(arr[i] == 0) {
                // Found zero.
                // Float it
                for(int j = i; j > prev; j--) {
                    int k = j - 1, temp = arr[k];
                    arr[k] = arr[j];
                    arr[j] = temp;
                }
                prev++;
            }
            i++;
        }

        for(i = 0; i < n; i++) {
            System.out.print(arr[i]);
            if(i != n - 1)
                System.out.print(" ");
        }
        System.out.println("");
    }
}

Count divisors of product of array elements

Given an array with N elements, the task is to find the count of factors of a number X which is product of all array elements.
Example:
Input : 2 4 6
Output : 10 2 * 4 * 6 = 48,the factors of 48 are 1, 2,
3, 4, 6, 8, 12, 16, 24, 48 whose count is 10.

Solution:
JAVA
import java.util.*;
import java.lang.*;
import java.io.*;

class Solution {
    static List<Integer> ll = new ArrayList<>();
    static  final int MAX = 101;
    static boolean[] isP = new boolean[MAX];
    static Scanner sc = new Scanner(System.in);
public static void main (String[] args) {
//code
init();
int n = sc.nextInt();

while(n-- > 0) solve();
}

public static void solve(){
    int n = sc.nextInt();
    if(n>0){
    int[] arr = new int[n];
    long ans = 1;
    int flag =0;
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for(int i = 0; i < n; i++){
        arr[i] = sc.nextInt();
        if(arr[i]>=1){
        flag=1;
        countFact(arr[i], map);
}
    }
    for(int key : map.keySet()){
        ans *= (map.get(key) + 1);
    }
    if(flag==1){
    System.out.println(ans);}
}
   
}
static void countFact(int n, Map<Integer, Integer> map){
    int i = 0;
    while(n != 1){
        while(n % ll.get(i) == 0){
            n = n / ll.get(i);
            map.put(ll.get(i),
                map.getOrDefault(ll.get(i), 0) + 1);
        }
        i++;
    }
}
static void init(){
    Arrays.fill(isP, true);
    isP[0] = isP[1] = false;
    for(int i = 2; i * i < MAX; i++){
        if(isP[i]){
            for(int j = i * i; j < MAX; j += i){
                isP[j] = false;
            }
        }
    }
    for(int i = 2; i < MAX; i++){
        if(isP[i]) ll.add(i);
    }
}
}

Reorganize The Array

Reorganize The Array :

Given an array of elements of length ​ N ​ , ranging from ​ 0 to N-1​ , your task is to write a program that rearranges the elements of the array. All elements may not be present in the array, if element is not present then there will be -1 present in the array. Rearrange the array such that A[i] = i and if i is not present, display -1 at that place.
Examples:
                   Input : arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1}
                   Output : {-1, 1, 2, 3, 4, -1, 6, -1, -1, 9}

Solution :
C
#include <stdio.h>
#include <stdlib.h>
int main() {
int T,i,n;
scanf("%d", &T);
while(T--) {
    scanf("%d", &n);
    int *arr,k;
    arr = (int *)calloc(n+1,sizeof(int));
    for(i = 0; i < n; i++) {
        scanf("%d", &k);
        if(k >= 0) {
            arr[k]++;
        }
    }
    for(i = 0; i < n; i++) {
        if(arr[i] > 0) {
            printf("%d ", i);
        }
        else {
            printf("-1 ");
        }
    }
    printf("\n");
}
return 0;
}

Loose Coupling & Tight Coupling in Programing


In programming as per the requirement we need to have multiple classes. So when there are multiple classes ,some classes will depend on other classes and some classes doesn't require any other classes help.

Loose Coupling : The name indicates that the class is single and doesn't depend on another class for its functionality. By using this you can isolate the things and make the changes easily because it is not depending on any other class

Tight Coupling : The name indicates that the class is not isolated and depends on multiple classes. This kind of coupling needs to be taken care because any change in one class must be notified by all other classes that are depending on that class.