Question of the Day - Calculate Inverse - 01/01/2023

 

Calculate Inverse

Problem Statement
Newton is given a sequence of N integers A1, A2, ... , AN
He wants to calculate the inverse of the sum of the inverses of the numbers i.e. 1⁄(1⁄A1 + 1⁄A2 +. . + 1⁄AN)
Help Newton with his unwanted curiosity and print the answer to the above equation.

    1-->Java
    import java.io.*;  
   import java.util.*;

class Main {
    public static void main (String[] args) {
        // Your code here
        Scanner sc=new Scanner(System.in);
        int N=sc.nextInt();
        int arr[]=new int[N];
        double sum=0;
        for(int i=0;i<N;i++)
        {
            arr[i]=sc.nextInt();
        }

        for(int i=0;i<N;i++) sum+=1.0/arr[i];
        
        System.out.printf("%.8f", + 1.0 / sum);
    }
}}
 
 JavaScript:
    
    
    // Your code here
    function main(data) {
      const input = data.split('\n');
      const ary = input[1].split(' ');
  
      var tmp = 0;
      for(var i = 0; i <input[0]; i++){
        tmp += 1/ary[i];
      }
      console.log(1/tmp);
}
    main(require('fs').readFileSync('/dev/stdin', 'utf8'));

    C:

    
    #include <stdio.h> // header file for Standard Input Output
    #include <stdlib.h> // header file for Standard Library

    int main() {
    //Your code here
    
     int n;
     scanf("%d",&n);
     double inverse=0;
     for(int i=1;i<=n;i++)
     {
        double x;
        scanf("%lf",&x);
        inverse=inverse+(1/x);
     }
     printf("%8f",(1/inverse));
     return 0;
    }

    Python:

    
    # Your code here
    n=int(input())
    a=list(map(int,input().split()))
    p=0
    for i in range(n):
        p+=1/a[i]
    print(1/p)

    C++:

    
    #include <bits/stdc++.h> // header file includes every Standard library
    using namespace std;

    int main() {
        // Your code here
      int n;
      cin>>n;
      int arr[n];
      for(int i=0;i<n;i++){
          cin>>arr[i];
      }
      double sum=0;
      for(int i=0;i<n;i++){
        sum+=(1.0/arr[i]);
      }
 
      double ans=1/sum;
      cout<<ans<<endl;
    return 0;
    }

    Above are the codes for the different programming languages. I have tried my best
   to provide the codes in C,C++,java,javascript and python. You can try with above
    codes. I'm not sure whether above all codes are working perfectly. You can do the
    changes with these codes if its not working.

No comments:

Powered by Blogger.