Как найти квадрат числа java

Описание

Метод Math.pow() – возводит значение первого аргумента в степень второго аргумента, тем самым позволяет осуществить быстрое возведение в степень любых значений.

Синтаксис

double pow(double base, double exponent)

Параметры

Подробная информация о параметрах:

  • base – любой примитивный тип данных.
  • exponent – любой примитивный тип данных.

Возвращаемое значение

  • В Java Math.pow() возвращает double значение первого аргумента, возведенное в степень второго аргумента.

Пример 1: возведение числа в квадрат и куб

Для возведения любого числа в квадрат с помощью метода Math.pow() необходимо в качестве второго аргумента использовать значение 2, а для возведения в куб – 3 и т.д. Заметьте, для вывода на экран целого значения используется «%.0f», так как метод возвращает double значение.

public class Test{ 

   public static void main(String args[]){
      // Возведение в квадрат числа 3  
      int a1 = 3;
      int b1 = 2;
      System.out.printf("Число 3 в квадрате равно %.0f n", Math.pow(a1, b1));
      
      // Возведение в квадрат числа 5  
      int a2 = 5;
      int b2 = 2;
      System.out.println("Число 5 в квадрате равно " + Math.pow(a2, b2));
      
      // Возведение в куб числа 2  
      int a3 = 2;
      int b3 = 3;
      System.out.printf("Число 2 в кубе равно %.0f n", Math.pow(a3, b3));
      
      // Возведение в куб числа 3  
      int a4 = 3;
      int b4 = 3;
      System.out.println("Число 3 в кубе равно " + Math.pow(a4, b4));
   }
}

Получим следующий результат:

Число 3 в квадрате равно 9 
Число 5 в квадрате равно 25.0
Число 2 в кубе равно 8 
Число 3 в кубе равно 27.0

Пример 2: возведение числа в дробную степень

public class Test{ 

   public static void main(String args[]){
      double x1 = 10.635;
      double y1 = 3.76;
      System.out.printf("Значение %.3f в степени %.2f равно %.3f n", x1, y1, Math.pow(x1, y1));
      System.out.printf("pow(%.3f, %.3f) = %.3f nn", x1, y1, Math.pow(x1, y1));
      
      int x2 = 2;
      double y2 = 3.76;
      System.out.printf("Значение 2 в степени %.2f равно %.3f n", y2, Math.pow(x2, y2));
      System.out.printf("pow(2, %.3f) = %.3f", y2, Math.pow(x2, y2));
   }
}

Получим следующий результат:

Значение 10,635 в степени 3,76 равно 7253,256 
pow(10,635, 3,760) = 7253,256 

Значение 2 в степени 3,76 равно 13,548 
pow(2, 3,760) = 13,548

Пример 3: возведение числа в отрицательную степень

public class Test{ 

   public static void main(String args[]){
      // Возведение числа в отрицательную дробную степень  
      double x = 7.525;
      double y = -1.49;
      System.out.printf("Значение %.3f в степени %.2f равно %.3f n", x, y, Math.pow(x, y));
      System.out.printf("pow(%.3f, %.3f) = %.3f nn", x, y, Math.pow(x, y));
      
      // Возведение числа в отрицательную степень 
      int a = 2;
      int b = -2;
      System.out.printf("Значение 2 в степени -2 равно %.2f n", Math.pow(a, b));
      System.out.printf("pow(2, -2) = %.2f", Math.pow(a, b));
   }
}

Получим следующий результат:

Значение 7,525 в степени -1,49 равно 0,049 
pow(7,525, -1,490) = 0,049 

Значение 2 в степени -2 равно 0,25 
pow(2, -2) = 0,25

Пример 4: возведение отрицательного числа степень

Заметьте, что при возведении отрицательного числа в дробную степень мы не получим результат (NaN).

public class Test{ 

   public static void main(String args[]){
      // Возведение отрицательного дробного числа в степень  
      double x1 = -7.525;
      double y1 = 1.49;
      System.out.printf("Значение %.3f в степени %.2f равно %.3f n", x1, y1, Math.pow(x1, y1));
      System.out.printf("pow(%.3f, %.3f) = %.3f nn", x1, y1, Math.pow(x1, y1));
      
      double x2 = -7.525;
      double y2 = 2;
      System.out.printf("Значение %.3f в степени %.0f равно %.3f n", x2, y2, Math.pow(x2, y2));
      System.out.printf("pow(%.3f, %.0f) = %.3f nn", x2, y2, Math.pow(x2, y2));
      
      double x3 = -7.525;
      double y3 = 3;
      System.out.printf("Значение %.3f в степени %.0f равно %.3f n", x3, y3, Math.pow(x3, y3));
      System.out.printf("pow(%.3f, %.0f) = %.3f nn", x3, y3, Math.pow(x3, y3));
      
      // Возведение отрицательного числа в степень 
      int a1 = -2;
      int b1 = 2;
      System.out.printf("Значение -2 в степени 2 равно %.0f n", Math.pow(a1, b1));
      System.out.printf("pow(-2, 2) = %.0f nn", Math.pow(a1, b1));
      
      int a2 = -2;
      int b2 = 3;
      System.out.printf("Значение -2 в степени 3 равно %.0f n", Math.pow(a2, b2));
      System.out.printf("pow(-2, 3) = %.0f", Math.pow(a2, b2));
   }
}

Получим следующий результат:

Значение -7,525 в степени 1,49 равно NaN 
pow(-7,525, 1,490) = NaN 

Значение -7,525 в степени 2 равно 56,626 
pow(-7,525, 2) = 56,626 

Значение -7,525 в степени 3 равно -426,108 
pow(-7,525, 3) = -426,108 

Значение -2 в степени 2 равно 4 
pow(-2, 2) = 4 

Значение -2 в степени 3 равно -8
pow(-2, 3) = -8

Пример 5: возведение каждого числа в квадрат и вывод на экран

public class Test{ 

   public static void main(String args[]){
      int a = 1; // Начальное число
      int b = 10; // Конечное число
      
      // Возведение каждого числа в квадрат и вывод на экран
      for (int i = a; i <= b; i++){
          System.out.printf("Значение " + i + " в квадрате равно %.0f n", Math.pow(i, 2));
      }
   }
}

Получим следующий результат:

Значение 1 в квадрате равно 1 
Значение 2 в квадрате равно 4 
Значение 3 в квадрате равно 9 
Значение 4 в квадрате равно 16 
Значение 5 в квадрате равно 25 
Значение 6 в квадрате равно 36 
Значение 7 в квадрате равно 49 
Значение 8 в квадрате равно 64 
Значение 9 в квадрате равно 81 
Значение 10 в квадрате равно 100 

В этой статье мы расскажем о том, как выполнять возведение в степень в языке программирования Java. Читателю будут представлены 5 актуальных способов решения поставленной задачи.

Но прежде чем мы приступим к перечислению способов, давайте для начала вспомним, что же вообще представляет собой операция возведения:

Таким образом, речь идет об умножении числа на свое же значение n-е количество раз. Умножаемое число — это основание степени, а количество операций по умножению — показатель. Результат такого перемножения и будет называться возведением в степень. Для числа 33 результат будет равен 27, так как 3 х 3 х 3 = 27.

Теперь давайте рассмотрим, как это все реализуется в языке программирования Java.

Math pow

Использование класса Math — наиболее простой вариант решения поставленной задачи. На практике его применяют в большинстве ситуаций. Public class Math включает в себя математические методы, в том числе те, которые связаны с геометрией и тригонометрией. В этом классе методы реализованы в качестве статических, следовательно, есть возможность вызывать их через имя класса Math, не создавая объект класса.

Смотрим код:

public static int pow(int value, int powValue) {

   return (int) Math.pow(value, powValue);

}

Здесь пришлось использовать операцию приведения типа (int), т. к. этот метод класса Math осуществляет возвращение значения типа double (аргументы, по сути, тоже double, однако там применяется неявное приведение типа).

Теперь рассмотрим несколько дополнительных вариантов решения поставленной задачи.

Значение квадрата числа

Начнем с наиболее простого и напишем метод по возведению в квадрат:

Выполняем вызов в main:

public static void main(String[] args) {

   System.out.println(Solution.pow(7));

}

Как видим, возведение в квадрат сложностей не вызывает.

Число в степени

Чаще всего нам приходится работать не с квадратным значением числа, а с числом в определенной степени. Усложним предыдущий вариант и задействуем кастомное Java pow-значение:

public static void main(String[] args) {

   System.out.println(Solution.pow(7, 4));

}

public static int pow(int value, int powValue) {

   int result = 1;

   for (int a = 1; а <= powValue; а++) {

       result = result * value;

   }

   return result;

}

Алгоритм несложен: мы как будто задаем точку отсчета result, а потом умножаем его на значение value столько, сколько будет работать цикл с powValue.

Рекурсия

Следующий вариант является уже более экзотичным.

Вы должны знать, что рекурсия позволяет методу осуществлять вызов самого себя. В языке программирования Java такие методы тоже есть и называются они рекурсивными.

На практике рекурсивно можно решать многие алгоритмические задачи. Наша — не исключение. Давайте выполним возведение в степень рекурсивно:

Как видно из реализации, существуют 2 момента:

  1. Условие выхода из рекурсии. Если возведенное значение степени достигает единицы, нас выбрасывает назад.
    1. Непосредственный механизм умножения value на результат вызова того же самого метода, однако с powValue — 1.

Для совсем ленивых разработчиков существуют способы «из коробки». Рассмотрим один из них.

BigInteger

BigInteger — это класс, который обеспечивает хранение целых чисел произвольной величины. Здесь существуют разные арифметические методы, которые позволяют работать с числами.

Выполняем возведение посредством BigInteger в Java:

Тут все предельно просто и не нуждается в дополнительных разъяснениях, не так ли? Однако на сегодня все, теперь вы будете знать о разных способах, позволяющих возводить в степень в «Джава».  

По материалам: https://javarush.ru/groups/posts/2828-kak-vihpolnitjh-vozvedenie-v-stepenjh-v-java.

Интересуют более продвинутые знания по языку программирования Java? Добро пожаловать на курсы в Otus!

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    The java.lang.Math.pow() is used to calculate a number raise to the power of some other number. This function accepts two parameters and returns the value of first parameter raised to the second parameter. There are some special cases as listed below:

    • If the second parameter is positive or negative zero then the result will be 1.0.
    • If the second parameter is 1.0 then the result will be same as that of the first parameter.
    • If the second parameter is NaN then the result will also be NaN.
    • The function java.lang.Math.pow() always returns a double datatype.

    Syntax:

    public static double pow(double a, double b)
    Parameter:
    a : this parameter is the base
    b : this parameter is the exponent.
    Return :
    This method returns ab.

    Example 1: To show working of java.lang.Math.pow() method. 

    Java

    import java.lang.Math;

    class Gfg {

        public static void main(String args[])

        {

            double a = 30;

            double b = 2;

            System.out.println(Math.pow(a, b));

            a = 3;

            b = 4;

            System.out.println(Math.pow(a, b));

            a = 2.5;

            b = 6.9;

            System.out.println(Math.pow(a, b));

        }

    }

    Output:

    900.0
    81.0
    556.9113382296638

    Time Complexity: O(log(b))

    Auxiliary Space: O(1)

    Java

    import java.lang.Math;

    public class GFG {

        public static void main(String[] args)

        {

            double nan = Double.NaN;

            double result;

            result = Math.pow(2, nan);

            System.out.println(result);

            result = Math.pow(1254, 0);

            System.out.println(result);

            result = Math.pow(5, 1);

            System.out.println(result);

        }

    }

    Output:

    NaN
    1.0
    5.0

    Time Complexity: O(log(b))

    Auxiliary Space: O(1)

    Last Updated :
    06 Feb, 2023

    Like Article

    Save Article

    Данная статья написана командой Vertex Academy. Это одна из статей из нашего «Самоучителя по Java.»


    Условие задачи:

    Написать метод возведения числа в квадрат. Например,

    И далее к результату прибавить число 2.

    Например,

    • если Вы ввели число 2, тогда в консоль должно быть выведено число 4 и 6
    • если Вы ввели число 3, тогда в консоль должно быть выведено число 9 и 11
    • если Вы ввели число 5, тогда в консоль должно быть выведено число 25 и 27
    • и т.д.

    Решение — 1й подход:

    public class Test{

     static int square(int a){

         int result = a*a;

         return result;

     }    

     public static void main(String[] args){

         int a1 = square(5);

         System.out.println(a1);

         System.out.println(a1 + 2);

     }

    }

    Если Вы запустите данный код, в консоли Вы увидите:

    25

    27

    Комментарии к задаче:

    Начиная решать данную задачу, необходимо попробовать вывести общую формулу возведения числа в квадрат. Как видите, общая формула возведения числа в квадрат выглядит как a*a.

    Именно поэтому мы написали метод square (с англ. square — возведение в квадрат), вот так:

    static int square(int a){

    int result = a*a;

    return result;

    В данной строчке мы принимаем число, которое необходимо возвести в квадрат. Причем, число должно быть целочисленным, поскольку мы указали int a:

    Далее мы прописали, что данное число необходимо умножить на себя. Для этого мы прописали:

    И далее вызываем метод square():

    public static void main(String[] args){

         int a1 = square(5);

         System.out.println(a1);

         System.out.println(a1 + 2);

     }

    Как видите, мы в этом примере возводим число 5 в квадрат. Результат возведения в квадрат числа 5, то есть число 25, мы «записываем» в переменную a1.

    Далее с помощью

    будет выведено в консоль число 25.

    И после этого с помощью

    System.out.println(a1 + 2);

    будет выведено в консоль число 27.

    Решение — 2-й подход:

    public class Test{

     static int square(int a){

         return a*a;

     }    

     public static void main(String[] args){

         System.out.println( square(5) );

         System.out.println( square(5) + 2 );

     }

    }

    Комментарии к задаче:

    Как видите, в этом подходе, в отличие от 1-го подхода, который мы рассмотрели выше, Вы просто вот эту часть кода

    static int square(int a){

         int result = a*a;

         return result;

     }

    заменили на

    static int square(int a){

    return a*a;

    }

    То есть сразу в return записали формулу возведения в квадрат a*a.

    И, соответственно, вот этот код из 1-го подхода

    public static void main(String[] args){

         int a1 = square(5);

         System.out.println(a1);

         System.out.println(a1 + 2);

     }

    заменили на

    public static void main(String[] args){

    System.out.println( square(5) );

    System.out.println( square(5) + 2 );

    }

    И таким образом сократили число строчек в коде.  При этом код легко читаем.


    Надеемся — наша статья была Вам полезна. Есть возможность записаться на наши курсы по Java. Детальную информацию смотрите у нас на сайте.

    One of the most popular frequently asked Java Interview Question is, “Given an integer x, write a java program to find the square root of it”. There are many ways to solve this problem. In this article, let’s check out different ways to find square and square root in Java.

    • What is Square and Square Root?
    • How to Square a Number in Java
      • By multiplying the number by itself
      • Using the Math.pow function
    • How to Find Square Root of a Number in Java
      • Using java.lang.Math.sqrt() method
      • By using Math.pow() function
      • Without using any inbuilt functions

    Before discussing the square root code in Java, let’s understand the term square root first.

    The square of a number is that number times itself. In other terms, when we multiply an integer by itself we call the product the square of the number. Mathematically,  the square of a number is given as, 

    Square of n = n*n

    For example, the square of number 4 is 4*4 = 16

    The square root is just the opposite of the square. The square root of a number, n, is the number that gives n when multiplied by itself. Mathematically, the square root of a number is given as, 

    Square Root of n = √n

    Now that you know what square and square root of a number are, let’s see different ways to calculate them in Java.

    How to Square a Number in Java

    You can square a number in Java in two different ways:

    1. Multiply the number by itself
    2. Call the Math.pow function

    Method1: Square a number by multiplying it by itself

    Here’s a Java Program to square a number by multiplying it by itself.

    package MyPackage; 
    import java.util.Scanner;
    
    public class Square1 {
    	public static void main(String args[]) {
    		
    		Double num;
    		Scanner sc= new Scanner(System.in);
    
    		System.out.print("Enter a number: ");
    		num=sc.nextDouble();
    		
    		Double square = num*num;
    		System.out.println("Square of "+ num + " is: "+ square);
    	}
    
    }
    

    Output

    Enter a number: 10
    Square of 10.0 is: 100.0
    

    Method2: Square a number with the Math.pow method

    Here’s a Java Program to call the Math.pow method to square a number.

    package MyPackage;
    import java.util.Scanner;
    import java.lang.Math; 
    
    public class Square2 {
    	
    public static void main(String args[]) {
    		
    		Double num;
    		Scanner sc= new Scanner(System.in);
    
    		System.out.print("Enter a number: ");
    		num = sc.nextDouble();
    		
    		Double square = Math.pow(num, 2);
    		System.out.println("Square of "+ num + " is: "+ square);
    }
    }
    

    Output

    Enter a number: 22
    Square of 22.0 is: 484.0
    

    Now let’s check out how to calculate the square root of a number in Java.

    How to Find Square Root of a Number in Java

    There are multiple ways to find square root a given number in Java. Let’s explore a few of those.

    Method1: Java Program to Find the square root of a Number using java.lang.Math.sqrt() method

    Syntax

    public static double sqrt(double x)

    • Parameter: x is the value whose square root is to be returned.
    • Return: This method returns the square root value of the argument passed to it.
      • If parameter x is positive double value, this method will return the square root of x
      • When x is NaN or less than zero, this method will return NaN
      • If parameter x is positive infinity, this method will return positive Infinity
      • When x is positive or negative zero, this method will return the result as Zero with the same sign

    Code

    package MyPackage;
    
    public class SquareRoot2 {
    
    	public static void main(String args[]) 
        { 
            double a = 100; 
      
            System.out.println(Math.sqrt(a));
            // Input positive value, Output square root of x  
      
            double b = -81.00; 
      
            System.out.println(Math.sqrt(b));
            // Input negative value, Output NaN  
      
            double c = 0.0/0; 
            // Input NaN, Output NaN  
      
            System.out.println(Math.sqrt(c)); 
      
            double d = 1.0/0;  
            // Input positive infinity, Output positive infinity   
      
            System.out.println(Math.sqrt(d)); 
            
            double e = 0.0;
            // Input positive Zero, Output positive zero  
            
            System.out.println(Math.sqrt(e)); 
        } 
    		
    }

    Output

    10.0
    NaN
    NaN
    Infinity
    0.0
    

    Method2: Java Program to Find the square root of a Number using java.lang.Math.pow() method

    We can use the logic √number = number½ to find the square root of a number.

    Code

    package MyPackage;
    
    import java.util.Scanner;
    
    public class SquareRoot1 {
    
    	public static void main(String[] args) 
    	{
    		Double num;
    		Scanner sc= new Scanner(System.in);
    
    		System.out.print("Enter a number: ");
    		num = sc.nextDouble();
    		
    		Double squareroot = Math.pow(num, 0.5);
    		System.out.println("The Square of a Given Number  " + num + "  =  " + squareroot);
    	}
    }
    

    Output

    Enter a number: 81
    The Square of a Given Number  81.0  =  9.0
    

    Method3: Java Program to Find the square root of a Number without using any in-built method

    Here’s the logic that we are using:

    Square Root - Square and Square Root in Java - -Edureka

    The first sqrt number should be the input number / 2. Here’s a Java Program implementing the above logic.

    Code

    package MyPackage;
    
    public class SquareRoot
    {
        
     public static double square(double number){
    	double t;
     
    	double squareroot = number / 2;
     
    	do {
    		t = squareroot;
    		squareroot = (t + (number / t)) / 2;
    	} while ((t - squareroot) != 0);
     
    	return squareroot;
    }
    
    public static void main(String[] args)
    {
        double number = 16;
        double root;
        root = square(number);
        System.out.println("Number : "+number);
        System.out.println("Square Root : "+root);
    }
    }

    Output

    Number : 121.0
    Square Root : 11.0
    

    This brings us to the end of this article. 

    Make sure you practice as much as possible and revert your experience.  

    Check out the Java Certification Course Online by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.

    Got a question for us? Please mention it in the comments section of this ‘Java sqrt() Method’ article and we will get back to you as soon as possible or you can also join Java Training in Dubai.

    Понравилась статья? Поделить с друзьями:

    Не пропустите также:

  • Как составить свой собственный комплекс тренировок
  • Как найти пещеру вардена в майнкрафт
  • Как найти свой компютер
  • Как найти адрес росгосстраха
  • Как найти язык в ворде

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии