Wednesday, March 7, 2012

Math function

Hi All

I'm trying to find a math function (if it exists) in SQL Server. If it
doesnt exist, then maybe someone can tell me what its called so I can
do a bit more reading on it

Basically I want to do this:

Parameter Components
1 1
2 2
3 1, 2
4 4
5 1, 4
6 2, 4
7 3, 4
8 8
9 1, 8
and so on

I'd like to be able to call a function and it would return true or
false like so

functionname(1, 9) = true
so 1 is a component of 9

functionname(2, 9) = false
so 2 is not a component of 9

functionname(4, 5) = true
so 4 is a component of 5

If anyone could tell me if it exists in C#, VB.NET, VB6 or VBScript,
I'd appreciate it!

Thanks in advance

SamOn 27 Aug 2004 06:00:50 -0700, Samuel Hon wrote:

> Hi All
> I'm trying to find a math function (if it exists) in SQL Server. If it
> doesnt exist, then maybe someone can tell me what its called so I can
> do a bit more reading on it
> Basically I want to do this:
> Parameter Components
> 1 1
> 2 2
> 3 1, 2
> 4 4
> 5 1, 4
> 6 2, 4
> 7 3, 4
> 8 8
> 9 1, 8
> and so on
> I'd like to be able to call a function and it would return true or
> false like so
> functionname(1, 9) = true
> so 1 is a component of 9
> functionname(2, 9) = false
> so 2 is not a component of 9
> functionname(4, 5) = true
> so 4 is a component of 5
> If anyone could tell me if it exists in C#, VB.NET, VB6 or VBScript,
> I'd appreciate it!
> Thanks in advance
> Sam

Your example seems a little fuzzy, but it looks like you are saying that
the "components" of an integer n are the largest power of 2 <= n, and the
remainder when that power of 2 is subtracted from n.

If this is the case, then your function in VB.NET could be:

Public Function IsComponent(C as Integer, P as Integer) as Boolean
Dim L as integer = LargestPowerOfTwo(P)
If (C > 0) and ( (C = L) or (C = P-L) ) Then
Return True
Else
Return False
End If
End Function

Public Function LargestPowerOfTwo(X as Integer) As Integer
Dim I as Integer = 1
If X < 1 Then
Return 0
End if
Do While I*2 <= X
I = I * 2
Loop
Return I
End Function

This could easily be ported to any other language, including T-SQL should
you need it there.|||Hi Ross

Thanks for the reply

I found that the 'technique' I'm looking for is bitwise comparison.
Change the numbers to bits, and then compare

Sam

No comments:

Post a Comment