8239. Function – 1

 

Implement the function f(x) = x3 + 2 * x2 – 3.

 

Input. Each line contains one real number x.

 

Output. For each value of x, print the value of the function f(x) on a separate line with four decimal places.

 

Sample input

Sample output

2.234

1

56

23.2

18.1309

0.0000

181885.0000

13560.6480

 

 

SOLUTION

functions

 

Algorithm analysis

The problem can be solved in two ways:

·        using a loop: read x and print the value of f(x) on the fly;

·        implement f(x) as a function;

Read the input data until the end of the file.

 

Algorithm implementation

Read the input data until the end of the file.

 

while(scanf("%lf",&x) == 1)

{

 

For each test case compute and print the answer.

 

  y = x * x * x + 2 * x * x  - 3;

  printf("%.4lf\n",y);

}

 

Algorithm implementation – function

Define the f function.

 

double f(double x)

{

  return x * x * x + 2 * x * x  - 3;

}

 

Read the input data until the end of the file. Compute and print the answer.

 

while(scanf("%lf",&x) == 1)

  printf("%.4lf\n",f(x));

 

Java implementation

 

import java.util.*;

 

public class Main

{

  static double f(double x)

  {

    return x * x * x + 2 * x * x  - 3;

  }

 

  public static void main(String[] args)

  {

    Scanner con = new Scanner(System.in);

    while(con.hasNext())

    {

      double x = con.nextDouble();

      System.out.println(f(x));

    }

    con.close();

  }

}  

 

Python implementation – function

 

import sys

 

Define the f function.

 

def f(x):

  return x ** 3 + 2 * x * x – 3

 

Read the input data until the end of the file. Compute and print the answer.

 

for x in sys.stdin:

  x = float(x)

  print(f(x))

 

Python implementation

 

import sys

 

Read the input data until the end of the file.

 

for x in sys.stdin:

 

For each test case compute and print the answer.

 

  x = float(x)

  y = x ** 3 + 2 * x * x – 3

  print(y)