0

I am a beginner of programming language. Right now, I am working on a Scala project, which requires us to calculate the sum of the product and the exponentiation of two non-negative integers without using any Math functions and signs but only allows to use successor and predecessor. The functions do count for us. So I need to define addition in terms of those two integers, then define multiplication in terms of addition and exponents in terms of multiplication. So far, I've only come up with the solution for getting sum. Could you please help me to obtain the other parts? I think (if firstNum = 1, secondNum = 3) the product of these two can be obtained by using sum_1(sum_1(sum_1(a,0),a),a) But I really don't know how to write it in Scala code. Many thanks!

import io.StdIn._

val num = readLine("\n\nFor counting the sum, multiplication and exponentiation of two integers.\nPlease enter those two integers in (x,y) format: ")
val comma = num.indexOf(",")

val last = num.indexOf(")")
val firstNum = num.substring(1,comma).toInt
val secondNum = num.substring(comma+1,last).toInt

def sum_1(a:Int,b:Int): Int = {
  def succ(a:Int): Int = a + 1
  def pred(b:Int): Int = b - 1
  if (b < 1) a
  else {
    succ(a)
    pred(b)
    sum_1(succ(a), pred(b))
  }
}


//multiplication


//exponentation


println("1.The sum is " + sum_1(firstNum, secondNum) + ".")
println("2.The multiplication is .")
println("3.The exponentation is .")

2 Answers 2

2

You will have the following set of functions:

def succ(a:Int) = a+1

def pred(a:Int) = a-1

def sum(a:Int,b:Int):Int =
  if(b<1) a
  else sum(succ(a),pred(b))

def mul(a:Int,b:Int):Int =
  if(b==0) 0 
  else if(b==1) a
  else sum(mul(a,pred(b)),a)

def exp(a:Int, b:Int):Int =
  if(b<1) 1
  else mul(exp(a,pred(b)),a)
1
  • Thank you so much for your help!
    – sytuacnh
    Oct 7, 2015 at 17:16
0
object mult extends App {

  def succ(a: Int): Int = a + 1
  def pred(b: Int): Int = b - 1
  def sum(a: Int, b: Int): Int =
    if (a == 0) b else sum(pred(a), succ(b))
  def mult(a: Int, b: Int): Int =
      if (a == 0) 0 else if (a == 1) b else sum(mult(pred(a), b), b)
  def exp(a: Int, b: Int): Int =
    if (b == 0) 1 else if (b == 1) a else mult(exp(a, pred(b)), a)

  def printmult(a: Int, b: Int): Unit = println(s"$a * $b = ${mult(a, b)}")
  (0 to 3).foreach { a => (0 to 3).foreach { b => printmult(a, b) } }

  def printexp(a: Int, b: Int): Unit = println(s"$a ^ $b = ${exp(a, b)}")
  (0 to 3).foreach { a => (0 to 3).foreach { b => printexp(a, b) } }

}
1
  • Thanks John! Thank you so much!
    – sytuacnh
    Oct 7, 2015 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.