# Challenge :

Your job is to find the given number N.

# Input :

You will be given a string in the following form:

dN ± Y = X


Where:

d, N, X, Y are all numbers with d , X , Y being integers (not decimals).


# Output :

Solve the equation and output the value of N rounded. Round up if decimal is greater than or equal to 0.5 and round down if less than 0.5

# Examples :

Input                  Output
N + 1 = 3        ---> 2
N - 1 = 5        ---> 6
2N + 1 = 3        ---> 1
2N + 1 = 4        ---> 2


# Winning criteria :

This is so the shortest code in each language wins.

# Notes :

• Answer must be rounded it cannot be a float
• Whitespace do not matter. You can have every element in the string separated by white space if you want or if you don't want leave it as it is.
• You do not need to check for invalid input. i.e. All inputs will be strings in the given format.

• Comments are not for extended discussion; this conversation has been moved to chat.
– user45941
Commented Apr 19, 2018 at 2:31
• @Mego : I have (hopefully) made it more clear. Can you kindly take a look and open it? Commented Apr 19, 2018 at 7:08
• @MuhammadSalman I'll leave both the original and add the alternative [-128,127] range answer then. (And I will delete some of my answers now, thanks for answering them.) Commented May 25, 2018 at 12:26
• Can d , X , and Y be negative? what is the maximum value that needs to be handled? Commented May 25, 2018 at 13:23
• @TaylorScott : If you want you can implement that. Commented May 25, 2018 at 13:30

# Python 2, 8874 70 bytes

-14 bytes thanks to Chas Brown.
-4 bytes thanks to Sunny Patel.

d,w,Y,_,X=input().split()
print round((int(X)-int(w+Y))/float(d[:-1]))


Try it online!

• @ovs : He he broke it. If I remove even a single space bam. It blows up. This is whitespace sensitive. Commented Apr 16, 2018 at 18:54
• @MuhammadSalman This was the case before. This solution requires at least one space between the different parts. If this is not allowed I will delete my answer.
– ovs
Commented Apr 16, 2018 at 19:02
• @ovs: Na it is perfectly alright. Commented Apr 16, 2018 at 19:04

under the assumption (according to comments) that we deal only with digits

# JavaScript (Node.js), 30 bytes

*thanks for @Rick Hitchcock for pointing out i can use 1 instead of space (reduces 13 bytes

x=>(x[3]+x[5]-x[9])/-x[0]+.5|0


Try it online!

# Python 2, 64 63 bytes

Using eval

d,w,Y,_,X=input().split()
print-eval('('+w+Y+'-'+X+')/'+d[:-1])


Try it online!

Saved 1 byte thanks to Keyu Gan

# Java 10, 111 94 (or 92) bytes

s->{var a=s.split("N|=");return(int)((new Float(a[2])-new Float(a[1]))/new Float(a[0])+.5);}


Input is in the format dN±Y=X (without any spaces) instead of dN ± Y = X.

Try it online.

2 more bytes could be saved if the numbers are never outside the [-128, 127] range, in which case the last and one of the two first Float can be changed to Byte.
Try it online.

Explanation:

s->{                             // Method with String parameter and integer return-type
var a=s.split("N|=");          //  And split by "N" or "=" to a String-array
return(int)((new Float(a[2])   //  Return the third number (after the equal sign),
-new Float(a[1])) //   minus the second number (including leading +/-),
/new Float(a[0])   //   divided by the first number
+.5);}                  //  Rounded by using (int)(R + 0.5)


# Japt v2.0a0, 20 bytes

q/N|=/ f
o!-Uo)r!÷ r


Try it

q/N|=/ f\no!-Uo)r!÷ r     :Implicit input of string U
: e.g. "2N+1=4"  "N+1=4"
q                         :Split on
/N|=/                    :  "N" or "="
> ["2","+1","4"] ["","+1","4"]
f                  :Filter (removes the first element if the string started with "N")
> ["2","+1","4"] ["+1","4"]
\n                :Reassign to U
Uo           :Pop last element (X)
> "4"            "4"
o               :Modify last element (Y)
!-             :X-Y
> ["2",3]        [3]
r         :Reduce by
!÷       :  Inverse division
> 1.5            3
r     :Round
> 2              3


# Wolfram Language (Mathematica), 54 46 bytes

Round[ToExpression[""<>(#/."="->"-")]~Root~1]&


Try it online!

# JavaScript (Node.js), 44 bytes

x=>([m,a,r]=x.split(/N|=/),r-a)/(+m||1)+.5|0


Try it online!

Or, for only single-digit numbers:

# JavaScript (Node.js), 36 bytes

([m,,o,a,,r])=>-(o+a-r)/(+m||1)+.5|0


Try it online!

# C (clang), 133 bytes

N,d,y,x,a[9],o;f(*s){sscanf(s," %[0-9N] %c %d = %d",a,&o,&y,&x);d=!sscanf(a,"%d",&d)?1:d;N=(x-(o>43?-y:y))*2/d;printf("%d",N/2+N%2);}


Try it online!

This handles all spaces except between d and N.

[Removed wrong answer that rounds down]

• some spaces can be removed
– l4m2
Commented May 26, 2018 at 1:41
• 124 bytes Commented Nov 23, 2018 at 19:43

# Befunge-93 (FBBI), 34 26 bytes

&~$~90p0&X&-2*\/-:2%\2/+.@  Try it online! If we didn’t need to bother with rounding correctly, it could be much smaller: &~$~90p0&X&-\/-.@


Try it online!

-\/-

• I think this fails to round, and instead truncates. For example, it returns 0 for 3N+1=3 when it should round 2/3 up to 1 Commented Apr 17, 2018 at 21:45
– Jo King
Commented Apr 18, 2018 at 7:16
• For rounding, you can double the numerator before dividing, add the quotient to itself mod 2, and then divide the sum of that by 2, instead of doing the multiply by 10 thing Commented Apr 18, 2018 at 21:11
• np, always happy to help Commented Apr 18, 2018 at 23:40

# Yabasic, 142 bytes

An anonymous function that takes input as a string and outputs to the console.

Line Input""s$dim n$(5)
k=token(s$,n$())
n$=n$(1)
If n$="N"n$=("1N")
?Int((Val(n$(5))-Val(n$(2)+"1")*Val(n$(3)))/Val(Left$(n$,Len(n$)-1))+.5)


Try it online!

# Vyxal, 110 bits1, 13.75 bytes

‛Nx*\=/ƒ∆qh.1+ṙ


Try it Online!

Python rounding is a little goofy hence the .1+ṙ at the end.

Could be 9.125 bytes: ‛Nx*\=/ƒ∆q if it wasn't for rounding.

## Explained

‛Nx*\=/ƒ∆qh.1+ṙ
‛Nx*            # Replace all N with x
\=/         # split on equal sign
ƒ∆q      # and solve the equation for x. Yes. There's a built in for it.
h.1+  # add 0.1 to the result to account for the fact that python seems to round down if <= 0.5 instead of < 0.5
ṙ # round the answer as required


# Scala 3, 168 bytes

import java.lang._
import scala.util.chaining._
val c:String=>Int=_.split("N|=").pipe(a=>(new Float(a(2))-new Float(a(1)))/new Float(a(0))).pipe(x=>math.round(x).toInt)


Attempt This Online!

• I thought scala._ and java.lang._ were imported by default
– user
Commented May 11, 2023 at 3:17

# [Matlab], 91 bytes

this is the most resilient version.

assuming that s is the input string.

syms N;v=str2double(regexp(s,'(?<!\d)(\d)+(?!\d)','match'));round(solve(v(1)*N+v(2)==v(3)))


# [Matlab], 74 bytes

syms N;round(solve(str2double(s(1))*N+str2double(s(4))==str2double(s(6))))


but doesnt really work if for example Y was 2 digits (ie 10). I'll try to improve it a bit.

# [Matlab], 29 bytes

if the input was just the numbers and not a string

sym N;round(solve(d*N+Y==X))


# Convex, 19 bytes

S-®-?\d+"ô:d~\-\/mo


Try it online!

# PHP, 45 bytes

<?=round((($s=$argn)[3].$s[5]-$s[9])/-$s[0]);  Run with echo '<input>' | php -nF <filename> or Try it online. This requires that d always be given, and that the string is the same length each time, e.g.: • N + 1 = 3 won't work, but 1N + 1 = 3 will work. • 1N +1 =3 won't work, but 1N + 1 = 3 will work. # J, 26 Bytes <.({.%~{:-1&{)".>0 2 4{cut  Note that the result for N is floored (not rounded), so for the last test case it returns 1 instead of 2. If this is unacceptable I will change the answer. Input should be of the form 'd N +-Y = X' ### Explanation:  cut '10 N +2 = 23' NB. Split on whitespace ┌──┬─┬──┬─┬──┐ │10│N│+2│=│23│ └──┴─┴──┴─┴──┘ 0 2 4{cut '10 N +2 = 23' NB. Choose relevant portions ┌──┬──┬──┐ │10│+2│23│ └──┴──┴──┘ ".>0 2 4{cut '10 N +2 = 23' NB. Eval each 10 2 23 ({.%~{:-1&{)".>0 2 4{cut'10 N +2 = 23' NB. Compute (x-y)/d 2.1 <.({.%~{:-1&{)".>0 2 4{cut'10 N +2 = 23' NB. Floor 2  ## C# (149 Bytes) s=>(int)Math.Round(((s=s.Replace(" ",""))[s.Length-1]-48-((s.Contains("-")?-1:1)*(s.Split(new[]{'+','-'})[1][0]-48)))/(decimal)(s[0]=='N'?1:s[0]-48))  Craptacular bloated C# solution. Guess I could've ported the Java solution but I try not to look at others' stuff before posting mine, so here we are. Try it Online # Ruby, 66 bytes ->s{a,_,b,_,c=s.split.map &:to_f;((s[?+]?c-b:c+b)/(a+0**a)).round}  Try it online! # awk, 48 bytes awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'  Use cases: echo "N + 1 = 3" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}' echo "N - 1 = 5" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}' echo "2N + 1 = 3" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}' echo "2N + 1 = 4" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'  Extra case: echo "3N + 1 = 11" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'  Output: 3 ## PHP, 83 Bytes Try it online Try it online2 For some reason round does not round to the closest integer on tio run, on this version the solution has some extra bytes (87 Bytes) Code <?=round(($c=explode(" ",$argv))[4]-($c[1].$c[2]))/($c[0]==N?1:substr($c[0],0,-1));  Explanation //ecuation structure xN sign c = m //array structure like ["xN","sign", "c", "=", "m"] round( //round the result ( //first element of the ecuation$c=explode(" ",$argv))[4] //explode the string and get the 4th value - //substract, php accepts (1-(-1)) so, //it can ve solved like this ($c[1].$c[2]) //concat the sign with c ) / //divide by x ($c[0]==N?1:substr($c[0],0,-1) //if the first element xN it's N //divide by 1, else remove N and divide );  Question About negative numbers, my code should work for an equation like -xN +- c = m, but when you are considering a x = -1, the input will be -N +- c = m or -1N +- c = m? # R, 90 bytes -round(eval(parse(t=gsub("=","-",gsub("\\dN","",s<-scan(,"")))))/(gsub("N.*$","",s):1)[1])


Try it online!

Assumes d is present as per the spec. Probably not the shortest option - I am sure there are better regex.

awk : safe division without branching ternary condition

echo 'N + 1 = 3' |

gawk '$__=sprintf("%.f",($5-($2$3))/(_+=$_)^!!_)' mawk '{printf("%.f",($5-($2$3))/(_+=$_)^!!_)}'  2  echo '2N + 1 = 4' | nawk '$!NF=sprintf("%.f",($5-($2$3))/(_+=$!_)^!!_)'


2