How to find square root, log recursively???

I need to find the square root of a number entered recursively and log as well. Your help would be greatly appreciated. Thanks in advance!
import java.io.*;
/**Class provides recursive versions
* of simple arithmetic operations.
public class Ops2
     private static BufferedReader in = null;
     /**successor, return n + 1*/
     public static int suc(int n)
          return n + 1;
     /**predecessor, return n - 1*/
     public static int pre(int n)
          if (n == 0)
               return 0;
          else
               return n - 1;
     /**add two numbers entered*/
     public static int add(int n, int m)
          if (m == 0)
               return n;
          else
               return suc(add(n, pre(m)));
     /**subtract two numbers entered*/
     public static int sub(int n, int m)
          if (n < m)
               return 0;
          else if (m == 0)
               return n;
          else
               return pre(sub(n, pre(m)));
     /**multiply two numbers entered*/
     public static int mult(int n, int m)
          if (m == 0)
               return 0;
          else
               return add(mult(n, pre(m)), n);
     /**divide two numbers entered*/
     public static int div(int n, int m)
          if (n < m)
               return 0;
          else
               return suc(div(sub(n, m), m));
     /**raise first number to second number*/
     public static int exp(int n, int m)
          if (m == 0)
               return 1;
          else
               return mult(exp(n, pre(m)), n);
     /**log of number entered*/
     public static int log(int n)
          if (n < 2)
               return 0;
          else
               return suc(log(div(n, 2)));
     /**square root of number entered*/
     public static int sqrt(int n)
          if (n == 0)
               return 0;
          else
               return sqrt(div(n, ));
     /**remainder of first number entered divided by second number*/
     public static int mod(int n, int m)
          if (n < m)
               return 0;
          else
               return mod(div(n, pre(m)), m);
     public static void prt(String s)
          System.out.print(s);
     public static void prtln(String s)
          System.out.println(s);
     public static void main(String [ ] args)
          prtln("Welcome to the amazing calculator");
          prtln("It can add, multiply and do powers for");
          prtln("naturals (including 0). Note that all the");
          prtln("HARDWARE does is add 1 or substract 1 to any number!!");
          in = new BufferedReader(new InputStreamReader ( System.in ) );
          int It;
          while ( (It = getOp()) >= 0)
               prt("" + It + "\n");
        private static int getOp( )
        int first, second;
        String op;
        try
            System.out.println( "Enter operation:" );
            do
                op = in.readLine( );
            } while( op.length( ) == 0 );
         System.out.println( "Enter first number: " );
            first = Integer.parseInt( in.readLine( ) );
            System.out.println( "Enter second number: " );
            second = Integer.parseInt( in.readLine( ) );
         prtln("");
         prt(first + " " + op + " " + second + " = ");
            switch( op.charAt( 0 ) )
              case '+':
                return add(first, second);
              case '-':
                   return sub(first, second);
              case '*':
                return mult(first, second);
              case '/':
                   return div(first, second);
              case '^':
                return exp(first, second);
              case 'v':
                   return log(first);
              case 'q':
                   return sqrt(first);
              case '%':
                   return mod(first, second);
              case 's':
                   return suc(first);
              case 'p':
                   return pre(first);
              default:
                System.err.println( "Need +, *, or ^" );
                return -1;
        catch( IOException e )
            System.err.println( e );
            return  0;
}

Hi,
Is there any one to make a program for me in Turbo
C++ for Dos, which can calculate the square root of
any number without using the sqrt( ) or any ready
made functions.
The program should calculate the s.root of the number
by a formula or procedure defined by the user
(programmer).
Thanks.This is a Java forum!
If you want Java help:
1. Start your own thread.
2. Use code tags (above posting box) if you post code.
3. No one will write the program for you. We will help by answering your questions and giving advice on how to fix problems in code you wrote.
4. The formula you need to implement is given above by dizzy.

Similar Messages

  • How to take square root of it

    Hi Folks!
    Can anybody tell me how to take square root of this value "bi"?
    BigInteger bi = BigInteger.valueOf(2000000000);
    Thanks in advance.

    I wrote this simple sqrt function for BigInteger.
    * Returns the largest BigInteger, n, such that bigInt>=n*n.
    * If round is true, the function returns n+1 if it is closer to actual square root.
    * @param round if true, attempt to find a closer value by rounding up.
    * @return <tt>round ? round(sqrt(bigInt)) : floor(sqrt(bigInt))</tt>
    public static BigInteger sqrt(BigInteger bigInt, boolean round){
         BigInteger op = bigInt;
         BigInteger res = BigInteger.ZERO;
         BigInteger tmp;
         int shift = bigInt.bitLength()-1;     
         shift -= shift&1;
         // set one to highest power of 4 <= bigInt
         BigInteger one = BigInteger.ONE.shiftLeft(shift);
         while(one.signum()>0){
              tmp = res.add(one);
              if(op.compareTo(tmp)>=0){
                   op = op.subtract(tmp);
                   res = res.add(one.shiftLeft(1));
              res = res.shiftRight(1);
              one = one.shiftRight(2);
         if(round&&op.signum()!=0){
              op = bigInt.subtract(res.pow(2));
              if(op.compareTo(res)>0){
                   res = res.add(BigInteger.ONE);
         return res;
    }

  • How to find 'Changes or LOGS on INFOCUBE'

    Dear Friends,
    How to find the changes on any INFOCUBE or ODS or MULTIPROVIDERS, like data loading, and any key figures, Chanractaeristics removed or added. Can we have any logs for the same. Pls help me.
    Thanks in Adavnace,
    DORA

    Hi Reddy,
    I did not find the log. Can you pls expand, how to do.
    Thanks in Adavance
    DORA

  • How to print square root ?

    Hi...i want to print square root on command prompt and a symbol(i don't know what it's name for second symbol). But i get a problem. Below is my code. For what i understand i should use \u221A right? :-
    public class Test
         public static void main(String[]args)
              try
                   System.out.println("\u221A");
                   System.out.println("\u00ea");
              catch(Exception e)
                   e.printStackTrace();
    }But the result is only question mark...can someone show me the right way and what's wrong to my code. I very appreciate to any help. Thank you.

    but it does show up in swing components
    import javax.swing.*;
    import java.awt.*;
    public class printsymb
         private static final String SYMBOL = String.valueOf( '\u221A' );
         public static void main( String args[] )
              display( SYMBOL );
              System.out.print( SYMBOL );
              System.out.println( 4 );
         private static void display( String symbol )
              JTextArea text = new JTextArea( symbol );
              JFrame f = new JFrame();
              f.add( text, BorderLayout.CENTER );
              enableJFrame( f );
         private static void enableJFrame( JFrame frame )
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.setSize( 320, 240 );
              frame.setVisible( true );
    }you can always put it out like this "sqrt(someExp)" can't you?
    Edited by: scphan on Apr 4, 2009 1:41 PM

  • How to find number of logged in users on NW04s?

    Ah, the fantastic search on sdn!!!
    I'm sure this has been asked before but I can't find it... (either the question or the answer)
    We have a J2EE application on NW2004s and I want to find how many users are logged on to the system.
    (it's not EP)
    Any quick answers will be appreciated and awarded.
    thnx
    kev

    Hello,
    to get list of active user in J2EE start telnet
    telnet <host> <telnet port>
    log in as j2ee_admin, administrator or with any user with administrator priviledges.
    to get list of available server nodes use command LSC.
    You can choose any node by using jump command followed by node id.
    execute for each node following commands:
    add servlet_jsp
    http_sessions full
    List of telnet commands:
    http://help.sap.com/saphelp_nw70ehp1/helpdata/en/4e/6e723964c11d45ad3aeca71482f084/frameset.htm
    Drabik Radovan

  • How to find the roots of other system in the network

    With out using RMI can we find the other system drive information(the roots available) from local(my) system..?

    public class roots{
    public static void main(String args[]) throws Exception
    System.out.println("The Drives are:");
    File[] roots = File.listRoots ();
         for (int i = 0; i < roots.length; i ++) {
         System.out.println (roots);
    This displaying the local system roots. Here how can i implement remote-filesystem protocol such as SMB or NFS .?
    I am not aware of this implementation as i am beginner ...
    kindly help me

  • How to find the root document of my web application, if it is in WAR file ?

    Hi,
    I want the root document of my web application. I my EAR file, i have only one WAR file. In my WAR file the following are the folders:-
    enterprise/..
    properties/sql/..
    locale/..
    WEB-INF/..
    Once i get the 'real path' or 'root document', I will use that in my application in no.of times. Path(root document) is used in the following way in my application:-
    File emailTemplatesFolder = new File( path + "/enterprise/"+ enterpriseCode+"/EmailTemplates");
    If i use getRealPath() method, it works fine, in use Oracle9ias, because, EAR file will be extracted. Where as in Weblogic 6.1, EAR file willn't be extracted, so that getRealPath() is giving 'null', that is reason why i am seeking for alternative.
    Thanks in Advance
    Srinivas

    Yes, that is the corrected behaviour.
    What you need to do is to get the ServletContext, and then load the files as resources.
    Here is how to load a properties file in the init() servlet method, which has access to the ServletConfig object that can give u the ServletContext.
    String classesDir = "/WEB-INF/classes";
    ServletContext sc = config.getServletContext();
    InputStram is = sc.getResourceAsStream(classesDir+"default.properties");
    props.load(is);
    Hope it helps,
    Liviu

  • How to find the root document in my application, if application is deployed as  EAR file ??

              Hi,
              I want the real path, i mean root document.
              I my EAR file, i have only one WAR file. In my WAR file the following are the
              folders:-
              enterprise/..
              properties/sql/..
              locale/..
              WEB-INF/..
              Once i get the 'real path' or 'root document', I will use that in application
              in no.of times. Path is used in the following way in our application:-
              File emailTemplatesFolder = new File( path + "/enterprise/"+ enterpriseCode+"/EmailTemplates");
              If i use getRealPath() method, it works fine, in use Oracle9ias, because, EAR
              file will be extracted. Where as in Weblogic 6.1, EAR file willn't be extracted,
              so that getRealPath() is giving 'null', that is reason why i am seeking for alternative.
              Thanks in Advance
              Srinivas
              

    Yes, that is the corrected behaviour.
    What you need to do is to get the ServletContext, and then load the files as resources.
    Here is how to load a properties file in the init() servlet method, which has access to the ServletConfig object that can give u the ServletContext.
    String classesDir = "/WEB-INF/classes";
    ServletContext sc = config.getServletContext();
    InputStram is = sc.getResourceAsStream(classesDir+"default.properties");
    props.load(is);
    Hope it helps,
    Liviu

  • How to find better SQL log in OBI Answers?

    While I have an error in making an OBI request in Answers page, the error message in the result tab is usually not very helpful, like:
    Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P:OI2DL65P
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 27005] Unresolved column: "Sales Facts Current Month"."Amount Sold (000) Current Month". (HY000)
    SQL Issued: {call NQSGetQueryColumnInfo('SELECT "Sales Facts Current Month"."Amount Sold (000) Current Month", "Sales Facts"."Amount Sold", Calendar."Calendar Month Desc", Calendar."Calendar Month Name", Products."Prod Category" FROM SH')}
    SQL Issued: SELECT "Sales Facts Current Month"."Amount Sold (000) Current Month", "Sales Facts"."Amount Sold", Calendar."Calendar Month Desc", Calendar."Calendar Month Name", Products."Prod Category" FROM SHI then go to Session Monitor, and click the View Log link. By doing so, sometimes, I got the full sql statement. That is good and I can figure out the problems. Sometimes, I have things like:
    -------------------- SQL Request:
    SET VARIABLE QUERY_SRC_CD='Report',SAW_SRC_PATH='/shared/sh/Learn';SELECT Times."Calendar Month Name" saw_0, Times."Calendar Month Desc" saw_1, Products."Prod Category" saw_2, Salesfacts."Amount Sold" saw_3, REPORT_SUM(saw_3 BY saw_0, saw_1), REPORT_SUM(saw_3 BY ) FROM SH WHERE (TOPN(Times."Calendar Month Id",40) <= 40) AND (Channels."Channel Desc" = 'Direct Sales') ORDER BY saw_1, saw_0, saw_2
    +++Administrator:13290000:1329000f:----2009/09/29 09:18:33
    -------------------- General Query Info:
    Repository: Star, Subject Area: SH, Presentation: SH
    +++Administrator:13290000:1329000f:----2009/09/29 09:18:33
    -------------------- Cache Hit on query:
    Matching Query:     SET VARIABLE QUERY_SRC_CD='Report';SELECT Times."Calendar Month Name" saw_0, Times."Calendar Month Desc" saw_1, Products."Prod Category" saw_2, Salesfacts."Amount Sold" saw_3 FROM SH WHERE (TOPN(Times."Calendar Month Id",40) <= 40) AND (Channels."Channel Desc" = 'Direct Sales') ORDER BY saw_0, saw_1, saw_2
    Created by:     AdministratorThis does not help as the selected tables are not fully spell out. It appear like that OBI find the sql in cache and did process the request fully.
    Is there a way I can force OBI resend the request? Is there a way to get OBI log the full sql statement? That way I can copy the sql to SQL*Plus and find exactly the problem
    Thanks.

    Physical SQL is not visible as it hits the cache.
    you can :
    1) clear the physical cache from rpd and re-run the request.
    or
    2) copy the logical SQL, go to web Admin - issue SQL--paste the logical SQL there, then just change one parameter or two, so it does not hit the cache. E.g. change a filter to Feb from Jan...or just add a dummy column at the beginning as select 1 or select 'a' ....rest of the sql same.
    this way you can avoid hitting the cache and see the sql (at the bottom of the results - view log)
    make sure you have checked the presentation server cache option and set the log level to 4 or more to see details.
    HTH

  • How to find the user logged on to machines in last 2 weeks,

    Hi All,
    I am running SCCM 2012 R2. I need your expert advice in a SQL query/sccm report.
    I have a list of about 1000 users. I need to find out the all the machines names that these user logged on to in last 2 weeks
    Hope you can help.
    Thanks
    Manish

    Hello,
    First, I don't this could be done with SCCM.
    If you have SCOM implement, it may help in this case. SCOM forum:
    https://social.technet.microsoft.com/Forums/systemcenter/en-US/home?category=systemcenteroperationsmanager
    In addition, logon information could be found in event log of DC. Audit the log with script could be another workaround.
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected]

  • How to find number of logged in users, using servlet

    Hello all,
    How can I find out how many users are successfully looged in on Tomcat server using JAVA technology ????
    Earliest suggestions are appreciated .............
    thnks in advance.......
    PhadkeA

    Maybe http://sourceforge.net/projects/big-brother/ could give you some hints.
    Haven't tried it yet.

  • How to find which Diagnostic Logging is turned on?

    Hello,
    When I am opening a supplier page, am getting a warning 'Low-level Diagnostic Logging is turned on. This may temporarily reduce performance'. Recently I did the following
    Enable FND Logging using system administrator responsibility by setting the
    following profiles at the USER Level.
    FND: Debug Log Enabled = Yes
    FND: Debug Log Level = Statement
    FND: Debug Log Module = %
    I am not sure about the earlier values of these profile system values. Is there a way to find out what profile values were changed?
    Thanks
    Raj

    Enable FND Logging using system administrator responsibility by setting the
    following profiles at the USER Level.
    FND: Debug Log Enabled = Yes
    FND: Debug Log Level = Statement
    FND: Debug Log Module = %
    I am not sure about the earlier values of these profile system values. Is there a way to find out what profile values were changed?Default values are:
    FND: Debug Log Enabled = No
    FND: Debug Log Level = Exception
    FND: Debug Log Module = %
    If you want to find out when those values were changed, you could get that from the application (Help > Record History) or query FND_PROFILE_OPTIONS_VL.
    Thanks,
    Hussein

  • How to find the deletion logs of RSBBS definition

    Hi Friends,
    In RSBBS, for one of the query the complete Assignment definition has been deleted by someone. Could you please let me know how we can identify when and from whom it got deleted?
    Regards
    Sushma

    HI,
    you will check the TX- SLG1 you will get all information about user.
    deleting, changing, modifying it will give all activity information.
    Thanks,
    phani.

  • To cancel logs in SM35 and find the root cause

    Hi,
    The role "PM****" is creating lot of sessions with the same session name and each session has hundreds of logs everyday in SM35. The logs is all about scheduling maintenance plans. There are hundreds of maintenance plans scheduling logs everyday. Can anyone help me how to find the root cause for this problem and stop the logs being generated in SM35?

    Hi,
    When you schedule RISTRA20 (transaction IP30) there are options for 'log control', check these and decide what level of logging you require.
    -Paul

  • How to find the configuration status of REDO logs files?

    I am in the process of moving the redo log files.
    Before that I want to find out whether it is set up as duplex or any other configurations.
    How to find the REDO log configurations.
    Oracle 10g R2
    Thank you,
    Smith

    Example:
    Not duplexed redo log - if number of member is 1, then it is not duplexed:
    SQL> select group#, members from v$log;
        GROUP#    MEMBERS
             1          1
             2          1
             3          1
    SQL> select group#, member from v$logfile;
        GROUP# MEMBER
             1 /u01/app/oracle/oradata/db1/redo01.log
             2 /u01/app/oracle/oradata/db1/redo02.log
             3 /u01/app/oracle/oradata/db1/redo03.log
    SQL> alter database add logfile member '/u01/app/oracle/oradata/db1/redo01_2.log' to group 1;
    Database altered.
    SQL> alter database add logfile member '/u01/app/oracle/oradata/db1/redo02_2.log' to group 2;
    Database altered.
    SQL> alter database add logfile member '/u01/app/oracle/oradata/db1/redo03_2.log' to group 3;
    Database altered.Duplexed redolog
    SQL> select group#, members from v$log;
        GROUP#    MEMBERS
             1          2
             2          2
             3          2
    SQL> select group#, member from v$logfile;
        GROUP# MEMBER
             1 /u01/app/oracle/oradata/db1/redo01.log
             2 /u01/app/oracle/oradata/db1/redo02.log
             3 /u01/app/oracle/oradata/db1/redo03.log
             1 /u01/app/oracle/oradata/db1/redo01_2.log
             2 /u01/app/oracle/oradata/db1/redo02_2.log
             3 /u01/app/oracle/oradata/db1/redo03_2.log

Maybe you are looking for