[RETO] IsFibonacciNumber(N as long) as Boolean

Iniciado por _katze_, Febrero 16, 2011, 08:51:59 PM

Tema anterior - Siguiente tema

0 Miembros y 3 Visitantes están viendo este tema.

este es un reto q esta en otro foro y la verdad para empesar a hacer algo lo vamos a hacer pero en .net

Para informacion acerca de la Secuencia de Fibonacci:
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
codigo de ejemplo para sugerir ideas pero esta en vb6 no hacer de esta manera
Código: php
Public Static Function IsFibonacci(ByVal lngNumber As Long) As Boolean
Dim dblRaised                                       As Double
Dim dblSum                                          As Double
Dim dblSqr                                          As Double

    dblRaised = lngNumber * lngNumber
    dblSum = dblRaised + dblRaised + dblRaised + dblRaised + dblRaised + &H4
    dblSqr = Sqr(dblSum)
    IsFibonacciMrFrog = (dblSqr - CLong(dblSqr) = &H0)
    If IsFibonacciMrFrog Then Exit Function
    dblSum = dblSum - &H8
    dblSqr = Sqr(dblSum)
    IsFibonacciMrFrog = (dblSqr - CLong(dblSqr) = &H0)
End Function

Febrero 17, 2011, 06:06:23 PM #1 Ultima modificación: Febrero 17, 2011, 08:26:56 PM por _katze_
che querido este es un ejemplo para una especie de chat entre dos dispositivos conectados a traves del serial port revisalo y cualquier cosa avisame
Código: vb
Imports System
Imports System.IO.Ports
Imports System.Threading

Public Class PortChat
    Shared _continue As Boolean
    Shared _serialPort As SerialPort

    Public Shared Sub Main()
        Dim name As String
        Dim message As String
        Dim sComparer As StringComparer = StringComparer.OrdinalIgnoreCase
        Dim readThread As Thread = New Thread(AddressOf Read)

        'Crear un nuevo objeto SerialPort con la configuración predeterminada.
        _serialPort = New SerialPort()

        'Permitir al usuario establecer las propiedades adecuadas.
        _serialPort.PortName = SetPortName(_serialPort.PortName)
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate)
        _serialPort.Parity = SetPortParity(_serialPort.Parity)
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits)
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits)
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake)

        'Juego de lectura / escritura tiempos de espera
        _serialPort.ReadTimeout = 500
        _serialPort.WriteTimeout = 500

        _serialPort.Open()
        _continue = True
        readThread.Start()

        Console.Write("Name: ")
        name = Console.ReadLine()

        Console.WriteLine("Type QUIT to exit")

        While (_continue)
            message = Console.ReadLine()

            If sComparer.Equals("quit", message) Then
                _continue = False
            Else
                _serialPort.WriteLine( _
                    String.Format("<{0}>: {1}", name, message))
            End If
        End While

        readThread.Join()
        _serialPort.Close()
    End Sub

    Public Shared Sub Read()
        While (_continue)
            Try
                Dim message As String = _serialPort.ReadLine()
                Console.WriteLine(message)
            Catch ex As TimeoutException
                'No hacer nada
            End Try
        End While
    End Sub

    Public Shared Function SetPortName(ByVal defaultPortName As String) As String
        Dim newPortName As String

        Console.WriteLine("Available Ports:")
        Dim s As String
        For Each s In SerialPort.GetPortNames()
            Console.WriteLine("   {0}", s)
        Next s

        Console.Write("COM port({0}): ", defaultPortName)
        newPortName = Console.ReadLine()

        If newPortName = "" Then
            newPortName = defaultPortName
        End If
        Return newPortName
    End Function

    Public Shared Function SetPortBaudRate(ByVal defaultPortBaudRate As Integer) As Integer
        Dim newBaudRate As String

        Console.Write("Baud Rate({0}): ", defaultPortBaudRate)
        newBaudRate = Console.ReadLine()

        If newBaudRate = "" Then
            newBaudRate = defaultPortBaudRate.ToString()
        End If

        Return Integer.Parse(newBaudRate)
    End Function

    Public Shared Function SetPortParity(ByVal defaultPortParity As Parity) As Parity
        Dim newParity As String

        Console.WriteLine("Available Parity options:")
        Dim s As String
        For Each s In [Enum].GetNames(GetType(Parity))
            Console.WriteLine("   {0}", s)
        Next s

        Console.Write("Parity({0}):", defaultPortParity.ToString())
        newparity = Console.ReadLine()

        If newparity = "" Then
            newparity = defaultPortParity.ToString()
        End If

        Return CType([Enum].Parse(GetType(Parity), newParity), Parity)
    End Function

    Public Shared Function SetPortDataBits(ByVal defaultPortDataBits As Integer) As Integer
        Dim newDataBits As String

        Console.Write("Data Bits({0}): ", defaultPortDataBits)
        newDataBits = Console.ReadLine()

        If newDataBits = "" Then
            newDataBits = defaultPortDataBits.ToString()
        End If

        Return Integer.Parse(newDataBits)
    End Function

    Public Shared Function SetPortStopBits(ByVal defaultPortStopBits As StopBits) As StopBits
        Dim newStopBits As String

        Console.WriteLine("Available Stop Bits options:")
        Dim s As String
        For Each s In [Enum].GetNames(GetType(StopBits))
            Console.WriteLine("   {0}", s)
        Next s

        Console.Write("Stop Bits({0}):", defaultPortStopBits.ToString())
        newStopBits = Console.ReadLine()

        If newStopBits = "" Then
            newStopBits = defaultPortStopBits.ToString()
        End If

        Return CType([Enum].Parse(GetType(StopBits), newStopBits), StopBits)
    End Function

    Public Shared Function SetPortHandshake(ByVal defaultPortHandshake As Handshake) As Handshake
        Dim newHandshake As String

        Console.WriteLine("Available Handshake options:")
        Dim s As String
        For Each s In [Enum].GetNames(GetType(Handshake))
            Console.WriteLine("   {0}", s)
        Next s

        Console.Write("Stop Bits({0}):", defaultPortHandshake.ToString())
        newHandshake = Console.ReadLine()

        If newHandshake = "" Then
            newHandshake = defaultPortHandshake.ToString()
        End If

        Return CType([Enum].Parse(GetType(Handshake), newHandshake), Handshake)
    End Function
End Class


espero tu respuesta
el koala :o

es amigo mio todo bn con lo q ponga.....che fakedoor te reto a q agas el reto

como te dije es muy dificil probar que este code funcione puesto que necesitas el puerto serie y lo que usa.....pero lo mirare un poco

Febrero 18, 2011, 10:26:24 AM #4 Ultima modificación: Febrero 18, 2011, 05:06:18 PM por Fakedo0r
No hagas doble post cabrona  :P , si pillo tiempo libre te dejo la funcion.  ;)


EDITO:

Aqui te dejo mi humilde funcion...

Código: php
Private Function IsFibonacciNumber(N As Long) As Boolean

    Dim X(2)    As Long
   
    X(Chr(48)) = Chr(48)
    X(Chr(49)) = Chr(49)
   
    If X(Chr(50)) = X(Chr(48)) Or X(Chr(49)) Then IsFibonacciNumber = True
    If X(Chr(50)) <> N Then IsFibonacciNumber = False
   
    For X(Chr(50)) = Chr(48) To N
       
        X(Chr(50)) = X(Chr(48)) + X(Chr(49))
        X(Chr(48)) = X(Chr(49))
        X(Chr(49)) = X(Chr(50))
       
        If X(Chr(50)) = N Then IsFibonacciNumber = True: Exit For

        DoEvents

    Next

End Function



Espero ver la tuya tambien.

Saludos...

Hace mil años ke no pasaba por aki Xd
Bueno, el tio Fake me ha retado a crearme una funcion de este tipo y como yo no soy de los ke dicen NO tan facilmente me dispuse toda la tarde a buscar el como y el porque de esta interesante serie de numeritos XD

Aka les dejo mi code con la funcion de Fibonacci y la comprovacion IsFibonacci (de la serie de Fibonacci), y claro un simple ejemplo pa ke vean como funkan XD

Código: php

Option Explicit

' By Jhonjhon_123 (J.J.G.P)
' Referencia: http://gaussianos.com/algunas-curiosidades-sobre-los-numeros-de-fibonacci/

Private Sub Form_Load()
Dim D As Long

' Serie de Fibonacci
For D = 1 To 34
    If isFibonacci(D) Then Debug.Print D, isFibonacci(D)
Next

' Formula de Fibonacci
For D = 0 To 9
    Debug.Print "N=" & D, "Fn=" & Fibonacci(D)
Next

End Sub

' Serie de Fibonacci
Private Function isFibonacci(Numero As Long) As Boolean
Dim D As Long
Dim CPerfecto(1) As Long
Dim EsPerfecto(1) As Boolean

CPerfecto(0) = 5 * (Numero ^ 2) - 4
CPerfecto(1) = 5 * (Numero ^ 2) + 4

For D = 0 To 1
    EsPerfecto(D) = Not CBool(CLng(Sqr(CPerfecto(D))) - Sqr(CPerfecto(D)))
Next

If EsPerfecto(0) Or EsPerfecto(1) Then isFibonacci = True
End Function

' Formula de Fibonacci
Private Function Fibonacci(n As Long) As Long
Dim Oro As Double
Oro = (1 + Sqr(5)) / 2
Fibonacci = ((Oro ^ n) - (-1 / Oro) ^ n) / Sqr(5)
End Function
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Febrero 24, 2011, 01:27:23 AM #6 Ultima modificación: Febrero 24, 2011, 01:54:04 AM por snifer
Se que me putearan en mil idiomas pero tengo flojera hacer correr la VM y lo unico que tengo a mano es el Gambas aunque me parecio mas facil hacerlo = en mono lo hare dentro de un rato ..

Código: Gambas
PUBLIC SUB Main()
' Serie de Fibo
DIM a,s,x,t AS Integer
DIM fibonacci AS String
  a= 0
  s=1
fibonacci = Str(a)&""&Str(s)
WHILE x <10 ' Para verificar el tamaño de la serie :P
t = a+s
x=x+1
WEND
PRINT fibonacci
END


BUeno aqui esta en c# --> mONO
Código: Mono

using System;

namespace Fibonnacci
{
class MainClass
{
public static void Main (string[] args)
{
long resultado, numero;
Console.WriteLine ("Ingresa la cantidad que desea la serie");
numero = long.Parse(Console.ReadLine());
resultado = fibo(numero);
Console.WriteLine ("Serie de fibonacci("+ numero +")="+ resultado);
Console.ReadLine();
}
static long fibo(long n)
{ if (n == 0 ||n ==1)
return n;
else
return fibo(n-1) + fibo(n-2);
}
}
}


No tienes permitido ver los links. Registrarse o Entrar a mi cuenta


Llaman traidor a la persona que evito que caiga el foro, gente bruta!