Page 1 of 2 12 LastLast
Results 1 to 40 of 52

Thread: [RESOLVED] Prime number code

  1. #1

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Resolved [RESOLVED] Prime number code

    Hey guys, I needed to make a program for finding prime numbers. The logic is that you have to put limits n & m and then LOOP and odd-integer P between n & m inclusive. I have a button to click on my form that displays 2 message boxes, one saying " enter upper limit" and the other say "enter lower limit". I need now to get the results of the odd prime numbers between the limits into a list box! How do I do that? Am I doing something wrong? I am new at the visual basic... I would appreciate your help. Thanks, S

    Code:
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            
            Dim Isprime As Integer
            Dim str As String
            Dim n As Integer
            Dim TestLimit As String
            Dim TestPrime As String
            Dim TestNum As String
    
    
            str = ""
            n = InputBox("Enter Upper limit")
            n = InputBox("Enter lower limit")
            If (n > 50) Then
                MsgBox("outside range")
                Exit Sub
    
            End If
    
            '   
            ' Eliminate even numbers
            If TestPrime Mod 2 = 0 Then Exit Sub
            '   Loop through ODD numbers starting with 3
            TestNum = 3
            TestLimit = TestPrime
            Do While TestLimit > TestNum
    
                If TestPrime Mod TestNum = 0 Then
                    '   Uncomment this if you really want to know
                    '   MsgBox "Divisible by " & TestNum   
    
                    Exit Sub
                End If
    
                '   There's logic to this.  Think about it.
                TestLimit = TestPrime \ TestNum
    
                '   Remember, we only bother to check odd numbers
                TestNum = TestNum + 2
    
            Loop
    
            '   If we made it through the loop, the number is a prime.
    
            Isprime = True
    
    
        End Sub

  2. #2
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Prime number code

    the returns from the input boxes have the same name "N"
    one of them should be "M"

    numbers should not be strings

    and odd numbers are every second number starting from an odd number so

    for x=<an odd number> to <an odd number> step 2
    will set x to odd numbers
    do your testing and ...
    if prime then list.additem x
    next x

  3. #3

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    oh your right.. thanks

    how do i incorporate what u said in the code?

    "for x=<an odd number> to <an odd number> step 2"

    do i plug in random values where u wrote odd number?

    im sorry im really new at this

  4. #4

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    oh your right.. thanks

    how do i incorporate what u said in the code?

    "for x=<an odd number> to <an odd number> step 2"

    do i plug in random values where u wrote odd number?

    im sorry im really new at this





    Quote Originally Posted by incidentals View Post
    the returns from the input boxes have the same name "N"
    one of them should be "M"

    numbers should not be strings

    and odd numbers are every second number starting from an odd number so

    for x=<an odd number> to <an odd number> step 2
    will set x to odd numbers
    do your testing and ...
    if prime then list.additem x
    next x

  5. #5
    PowerPoster Nightwalker83's Avatar
    Join Date
    Dec 2001
    Location
    Adelaide, Australia
    Posts
    13,344

    Re: Prime number code

    Try this:

    vb Code:
    1. Public Class Form1
    2.  
    3.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    4.        
    5.         Dim Isprime As Integer
    6.         Dim str As String
    7.         Dim m As Integer
    8.         Dim n As Integer
    9.         Dim TestLimit As String
    10.         Dim TestPrime As String
    11.         Dim TestNum As String
    12.  
    13.  
    14.         str = ""
    15.         m = InputBox("Enter Upper limit")
    16.         n = InputBox("Enter lower limit")
    17.         If (n > 50) Then
    18.             MsgBox("outside range")
    19.             Exit Sub
    20.  
    21.         End If
    22.  
    23.         '  
    24.         ' Eliminate even numbers
    25.         If TestPrime Mod 2 = 0 Then Exit Sub
    26.         '   Loop through ODD numbers starting with 3
    27.         TestNum = 3
    28.         TestLimit = TestPrime
    29.         Do While TestLimit > TestNum
    30.           for x= TestNum to  TestLimit step 2
    31.             If TestPrime Mod TestNum = 0 Then
    32.                 '   Uncomment this if you really want to know
    33.                 '   MsgBox "Divisible by " & TestNum  
    34.  
    35.                 Exit Sub
    36.             End If
    37.  
    38.             '   There's logic to this.  Think about it.
    39.             TestLimit = TestPrime \ TestNum
    40.  
    41.             '   Remember, we only bother to check odd numbers
    42.             TestNum = TestNum + 2
    43.            if prime then list.additem x
    44.              next x
    45.         Loop
    46.  
    47.         '   If we made it through the loop, the number is a prime.
    48.  
    49.         Isprime = True
    50.  
    51.  
    52.     End Sub

    I have requested the thread moved since you are using vb.net not vb6. Something such as that although, I haven't tested it so I can't be sure.
    when you quote a post could you please do it via the "Reply With Quote" button or if it multiple post click the "''+" button then "Reply With Quote" button.
    If this thread is finished with please mark it "Resolved" by selecting "Mark thread resolved" from the "Thread tools" drop-down menu.
    https://get.cryptobrowser.site/30/4111672

  6. #6

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    Thank you for the code!!
    you know where you put

    "if prime then list.additem x
    next x
    Loop"

    the prime is underlined saying prime is not declared. should i declare it as an integer? and "list.additemx" is underlined as well. do i have to declare x as an integer as well? and it also says that additem is not part of the application. how do i make it part of the application? So many questions sorry lol u have beena great help..


    Quote Originally Posted by Nightwalker83 View Post
    Try this:

    vb Code:
    1. Public Class Form1
    2.  
    3.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    4.        
    5.         Dim Isprime As Integer
    6.         Dim str As String
    7.         Dim m As Integer
    8.         Dim n As Integer
    9.         Dim TestLimit As String
    10.         Dim TestPrime As String
    11.         Dim TestNum As String
    12.  
    13.  
    14.         str = ""
    15.         m = InputBox("Enter Upper limit")
    16.         n = InputBox("Enter lower limit")
    17.         If (n > 50) Then
    18.             MsgBox("outside range")
    19.             Exit Sub
    20.  
    21.         End If
    22.  
    23.         '  
    24.         ' Eliminate even numbers
    25.         If TestPrime Mod 2 = 0 Then Exit Sub
    26.         '   Loop through ODD numbers starting with 3
    27.         TestNum = 3
    28.         TestLimit = TestPrime
    29.         Do While TestLimit > TestNum
    30.           for x= TestNum to  TestLimit step 2
    31.             If TestPrime Mod TestNum = 0 Then
    32.                 '   Uncomment this if you really want to know
    33.                 '   MsgBox "Divisible by " & TestNum  
    34.  
    35.                 Exit Sub
    36.             End If
    37.  
    38.             '   There's logic to this.  Think about it.
    39.             TestLimit = TestPrime \ TestNum
    40.  
    41.             '   Remember, we only bother to check odd numbers
    42.             TestNum = TestNum + 2
    43.            if prime then list.additem x
    44.              next x
    45.         Loop
    46.  
    47.         '   If we made it through the loop, the number is a prime.
    48.  
    49.         Isprime = True
    50.  
    51.  
    52.     End Sub

    I have requested the thread moved since you are using vb.net not vb6. Something such as that although, I haven't tested it so I can't be sure.

  7. #7
    PowerPoster Nightwalker83's Avatar
    Join Date
    Dec 2001
    Location
    Adelaide, Australia
    Posts
    13,344

    Re: Prime number code

    Should it be Isprime?
    when you quote a post could you please do it via the "Reply With Quote" button or if it multiple post click the "''+" button then "Reply With Quote" button.
    If this thread is finished with please mark it "Resolved" by selecting "Mark thread resolved" from the "Thread tools" drop-down menu.
    https://get.cryptobrowser.site/30/4111672

  8. #8

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    oh ya your right. thanks
    now for the x variable, it gives me this error
    "Error 1 Type of 'x' is ambiguous because the loop bounds and the step clause do not convert to the same type. C:\Users\Sharda\AppData\Local\Temporary Projects\WindowsApplication1\Form1.vb 35 17 WindowsApplication1
    "

    what should i do?
    ( you are so kind for answering these questions, i will give u the biggest thank you after this!!)


    Quote Originally Posted by Nightwalker83 View Post
    Should it be Isprime?

  9. #9
    PowerPoster Nightwalker83's Avatar
    Join Date
    Dec 2001
    Location
    Adelaide, Australia
    Posts
    13,344

    Re: Prime number code

    You need to add the following to your code:

    vb Code:
    1. Dim x As Integer

    Also, what is testprime? You haven't specified it anywhere.
    when you quote a post could you please do it via the "Reply With Quote" button or if it multiple post click the "''+" button then "Reply With Quote" button.
    If this thread is finished with please mark it "Resolved" by selecting "Mark thread resolved" from the "Thread tools" drop-down menu.
    https://get.cryptobrowser.site/30/4111672

  10. #10

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    ah ok

    test prime is if someone enters a random number, it is to test if the random number is a prime or not. does that make sense? its giving me a problem in the program also. one problem is popping up after the next. ive been working on this all day i cant get it right. do you have a better way to right the program for what i want? using loops of course. I would really appreciate it.

    (i

    Quote Originally Posted by Nightwalker83 View Post
    You need to add the following to your code:

    vb Code:
    1. Dim x As Integer

    Also, what is testprime? You haven't specified it anywhere.

  11. #11
    PowerPoster Nightwalker83's Avatar
    Join Date
    Dec 2001
    Location
    Adelaide, Australia
    Posts
    13,344

    Re: Prime number code

    Is testprime suppose to eqaul m or n? At the moment irt doesn't equal anything.
    when you quote a post could you please do it via the "Reply With Quote" button or if it multiple post click the "''+" button then "Reply With Quote" button.
    If this thread is finished with please mark it "Resolved" by selecting "Mark thread resolved" from the "Thread tools" drop-down menu.
    https://get.cryptobrowser.site/30/4111672

  12. #12
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: Prime number code

    Try this:

    vb Code:
    1. Public Class Form1
    2.  
    3.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    4.         Dim lb As Integer = 2
    5.         Dim ub As Integer = 50
    6.  
    7.         Dim isPrime As Boolean
    8.  
    9.         '~~~ read the numbers and convert it into integer numbers. Because InputBox() will always return Strings
    10.         lb = Integer.Parse(InputBox("Lower Limit ?"))
    11.         ub = Integer.Parse(InputBox("Upper Limit ?"))
    12.  
    13.         '~~~ Check whether it is in valid range
    14.         If lb < 2 OrElse ub > 50 Then
    15.             MessageBox.Show("Not a valid range !")
    16.             Exit Sub  '~~~ exit from the rest of the code
    17.         End If
    18.  
    19.         '~~~ loop through the numbers between Lower and Upper limits
    20.         For i As Integer = lb To ub
    21.             If Not i Mod 2 = 0 Then     '~~~ if it is even, skip that number
    22.                 isPrime = True          '~~~ assume it is true
    23.  
    24.                 '~~~ find whether it is divisible by any other number. If so, it is not prime
    25.                 For j As Integer = 3 To i - 1
    26.                     If i Mod j = 0 Then
    27.                         isPrime = False     '~~~ if divisible, it is not prime
    28.                         Exit For            '~~~ exit this inner for loop
    29.                     End If
    30.                 Next
    31.  
    32.                 '~~~ if prime, add it to listbox
    33.                 If isPrime = True Then ListBox1.Items.Add(i.ToString)
    34.             End If
    35.            
    36.         Next
    37.  
    38.     End Sub
    39. End Class
    I hope the comments included in the code will help you to understand it's working.

    BTW, this is a VB.net question. And you have posted in VB6 section. I'll request a mod to move this thread to the appropriate section.


    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  13. #13
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: Prime number code

    Moved to the VB.Net Forum. Thanks for the reports Nightwalker83 and akhileshbc

    Gary

  14. #14
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Prime number code

    Quote Originally Posted by shardooni View Post
    oh your right.. thanks

    how do i incorporate what u said in the code?

    "for x=<an odd number> to <an odd number> step 2"

    do i plug in random values where u wrote odd number?

    im sorry im really new at this
    sorry for delay...
    just had a huge power cut

    the example above is about using n and m

    but it expects the the limits ( the things being tested ) to be odd values

    so take the the next or previous values from n and m and use them in the loop

    if the loop goes from n to m then you only need

    Code:
    'alter n
    if n mod 2 = 0 then n=n+1
    you loop would be

    Code:
    for x=n to m step2
        'test x here to see if prime
        'if x is prime with your function isprime() then add to list
        if isprime(x) then list.additem x
    next
    as simple as that

    sorry for confusion

    I normally write psuedo code so that you do the thinking and final coding yourself

    here to talk

  15. #15

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    No problem, thanks for replying.
    I put what you said in my code, but im getting this error where i wrote " If isprime(x) Then List.additem(x)". it says that the expression "isprime" is not part of the array or method and cannot have an argument list? what did i do wrong now? lol
    Code:
            Dim str As String
            Dim m As Integer
            Dim n As Integer
            Dim TestLimit As String
            Dim TestPrime As String
            Dim TestNum As String
            Dim x As Integer
            Dim isprime As Integer
    
    
            str = ""
            m = InputBox("Enter Upper limit")
            n = InputBox("Enter lower limit")
            If (n > 50) Then
                MsgBox("outside range")
                Exit Sub
    
            End If
    
            '   
            ' Eliminate even numbers
            If n Mod 2 = 0 Then n = n + 1
    
            '   Loop through ODD numbers starting with 3
            TestNum = 3
            TestLimit = TestPrime
            Do While TestLimit > TestNum
                For x = TestNum To TestLimit Step 2
    
                Next
                If TestPrime Mod TestNum = 0 Then
                    '   Uncomment this if you really want to know
                    '   MsgBox "Divisible by " & TestNum   
    
                    Exit Sub
                End If
    
                '   There's logic to this.  Think about it.
                TestLimit = TestPrime \ TestNum
    
                '   Remember, we only bother to check odd numbers
                For x = n To m Step 2
                    'test x here to see if prime
                    'if x is prime with your function isprime() then add to list
    
                    If isprime(x) Then List.additem(x)
                Next
            Loop
    
            '   If we made it through the loop, the number is a prime.
    
            Isprime = True
    
        End Sub
    
        
    
    End Class

    Quote Originally Posted by incidentals View Post
    sorry for delay...
    just had a huge power cut

    the example above is about using n and m

    but it expects the the limits ( the things being tested ) to be odd values

    so take the the next or previous values from n and m and use them in the loop

    if the loop goes from n to m then you only need

    Code:
    'alter n
    if n mod 2 = 0 then n=n+1
    you loop would be

    Code:
    for x=n to m step2
        'test x here to see if prime
        'if x is prime with your function isprime() then add to list
        if isprime(x) then list.additem x
    next
    as simple as that

    sorry for confusion

    I normally write psuedo code so that you do the thinking and final coding yourself

    here to talk

  16. #16
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Prime number code

    your code is getting messed up

    you still have not grasped the concepts and are plugging stuff into your code in all the wrong places..

    I will have a look at the code in full... and get back to you

  17. #17
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: Prime number code

    Quote Originally Posted by shardooni View Post
    I put what you said in my code, but im getting this error where i wrote " If isprime(x) Then List.additem(x)". it says that the expression "isprime" is not part of the array or method and cannot have an argument list? what did i do wrong now? lol
    If you put something inside a bracket, it should either be an array or be a function. So, in your code, you tried to use:
    Code:
    If isprime(x) Then List.additem(x)
    At that line, the compiler can't find an array or function named "isprime". So it pops that error.

    In "incidentals"'s last post, he stated this psuedocode:

    Code:
    for x=n to m step2
        'test x here to see if prime
        'if x is prime with your function isprime() then add to list
        if isprime(x) then list.additem x
    next
    That means, he was expecting isprime as a function. So, create a function that will check whether a number passed to it as argument is prime or not. Then loop through the lower and upper limit, and call this function passing the number as argument. So, in the loop you will call the function and if it returns true(ie. the passed number is prime), add it to the ListBox.


    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  18. #18

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    sorry but my teacher hasnt taught us how to use any of this stuff! its all trial and error for me. he isnt responding to my emails either, so i need to ask people for help. i honestly am really bad at programming, im taking it as a complimentary and i will never do programming again in my life



    Quote Originally Posted by incidentals View Post
    your code is getting messed up

    you still have not grasped the concepts and are plugging stuff into your code in all the wrong places..

    I will have a look at the code in full... and get back to you

  19. #19
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Prime number code

    Code:
    	
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            
         
            Dim str As String ' dont know why you want this
            Dim n As Integer 'variable for the lower value
            Dim m As Integer 'variable for the upper value
    
            Dim TestLimit As String 'type all messed up
            Dim TestPrime As String 'type all messed up
            Dim TestNum As String   'type all messed
    
            Dim x As Integer 'unnecessary as x is a local counter value but good practice
    
            Dim isprime As boolean ' no its the result of a function and it will be a boolean
    
    
            str = "" 'why do you need this
            n = InputBox("Enter lower limit") ' ok lets getvthe first value
            m = InputBox("Enter Upper limit") ' ok lets get the next value
    
                                              ' good thats 2 value done, but no tests yet
                                              ' the actual output of the inboxes will be strings but the typing of n and m will cast them to integers
    
            If (n > 50) Then                  ' this test is inadequate you said n>2 and m<50, why only test >50
                MsgBox("outside range")       'message box should say n too big , still the wrong test though!
                Exit Sub
            End If
    
    '***********************************************************
    ' the 2 tests your spec setout are
    
    if n<2 then 
    msgbox("the lower limit is too small - start again")
    exit sub
    end if
    
    if m>50 then
    msgbox("the upperlimit is too big - start again")
    exit sub
    end if
    
    '***********************************************************
    
            '   
            ' Eliminate even numbers 
            If n Mod 2 = 0 Then n = n + 1 'this ensures your lowerlimit is odd to start from
    
            '   Loop through ODD numbers starting with 3  ' what is the lowerlimit was 23
    
    '***********************************************************
    'junk the loop
    
            TestNum = 3
            TestLimit = TestPrime
            Do While TestLimit > TestNum
                For x = TestNum To TestLimit Step 2
    
                Next
                If TestPrime Mod TestNum = 0 Then
                    '   Uncomment this if you really want to know
                    '   MsgBox "Divisible by " & TestNum   
    
                    Exit Sub
                End If
    
                '   There's logic to this.  Think about it.
                TestLimit = TestPrime \ TestNum
    
                '   Remember, we only bother to check odd numbers
                For x = n To m Step 2
                    'test x here to see if prime
                    'if x is prime with your function isprime() then add to list
    
                    If isprime(x) Then List.additem(x)
                Next
            Loop
    
            '   If we made it through the loop, the number is a prime.
    
            Isprime = True
    
    'end of junk
    '*****************************************************************************
    
    '*****************************************************************************
    'replacement loop 
    
    '   Remember, we only bother to check odd numbers
    
                For x = n To m Step 2                 ' this for does from an odd lowerlimit then +2,+4,+... up to the last odd number before the upperlimit
    
                    'test x here to see if prime
                    'if x is prime with your function isprime() then add to list
    
                    If isprime(x) Then List.additem(x) 'if the result of a new function called isprime is true then store the x that was tested in the listbox
                Next                                   ' loop some more
    
    
       End Sub
    
    
    'now you need to write the prime testing function
    
    I give you a start
    
    public function isprime(arg)as boolean
    
    isprime=false
    
    'do your test loop here
    'return true if arg is indeed prime with isprime=true
    
    end function
    
    End Class
    now its your turn read this remove extraneous stuff

    understand the way it works and then write the isprime function
    and then post it back and we will see where you have got to!

    here to talk

  20. #20
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: Prime number code

    Quote Originally Posted by shardooni View Post
    sorry but my teacher hasnt taught us how to use any of this stuff! its all trial and error for me. he isnt responding to my emails either, so i need to ask people for help. i honestly am really bad at programming, im taking it as a complimentary and i will never do programming again in my life
    No need to be ashamed of anything. Just follow some some good tutorials, understand it, try it out(in VB)... errors may pop out in some cases.. try to figure out what it says... try to solve it... if not successful, post it here... we'll help you..


    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  21. #21
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Prime number code

    agreed

    he is trying and thats what counts

    some people come exspecting to be given the answers

    apparently having done nothing but asked

    here to talk

  22. #22

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    Okay I did the last part for the "isprime". Is it right? this is all so confusing

    Code:
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim str As String ' dont know why you want this
            Dim n As Integer 'variable for the lower value
            Dim m As Integer 'variable for the upper value
    
            Dim TestLimit As String 'type all messed up
            Dim TestPrime As String 'type all messed up
            Dim TestNum As String   'type all messed
    
            Dim x As Integer 'unnecessary as x is a local counter value but good practice
    
            Dim isprime As Boolean ' no its the result of a function and it will be a boolean
    
    
            str = "" 'why do you need this
            n = InputBox("Enter lower limit") ' ok lets getvthe first value
            m = InputBox("Enter Upper limit") ' ok lets get the next value
    
            ' good thats 2 value done, but no tests yet
            ' the actual output of the inboxes will be strings but the typing of n and m will cast them to integers
    
    
            '***********************************************************
            ' the 2 tests your spec setout are
    
            If n < 2 Then
                msgbox("the lower limit is too small - start again")
                Exit Sub
            End If
    
            If m > 50 Then
                msgbox("the upperlimit is too big - start again")
                Exit Sub
            End If
    
            '***********************************************************
    
            '   
            ' Eliminate even numbers 
            If n Mod 2 = 0 Then n = n + 1 'this ensures your lowerlimit is odd to start from
    
            '   Loop through ODD numbers starting with 3  ' what is the lowerlimit was 23
    
            '***********************************************************
            'junk the loop
    
            TestNum = 3
            TestLimit = TestPrime
            Do While TestLimit > TestNum
                For x = TestNum To TestLimit Step 2
    
                Next
                If TestPrime Mod TestNum = 0 Then
                    '   Uncomment this if you really want to know
                    '   MsgBox "Divisible by " & TestNum   
    
                    Exit Sub
                End If
    
                '   There's logic to this.  Think about it.
                TestLimit = TestPrime \ TestNum
    
                '   Remember, we only bother to check odd numbers
                For x = n To m Step 2
                    'test x here to see if prime
                    'if x is prime with your function isprime() then add to list
    
                    If isprime(x) Then List.additem(x)
                Next
            Loop
    
            '   If we made it through the loop, the number is a prime.
    
            Isprime = True
    
            'end of junk
            '*****************************************************************************
    
            '*****************************************************************************
            'replacement loop 
    
            '   Remember, we only bother to check odd numbers
    
            For x = n To m Step 2                 ' this for does from an odd lowerlimit then +2,+4,+... up to the last odd number before the upperlimit
    
                'test x here to see if prime
                'if x is prime with your function isprime() then add to list
             
            Next
                If isprime(x) Then List.additem(x) 'if the result of a new function called isprime is true then store the x that was tested in the listbox
            ' loop some more
            
    
        End Sub
    
    
        'now you need to write the prime testing function
    
        'I give you a start
    
        Public Function isprime(ByVal arg) As Boolean
    
            Dim n As Integer
    
                   isprime = True             ' testing as long as true
            Dim F As Integer
            For F = 2 To n - 1
                If n Mod F = 0 Then
                    isprime = False   ' divisible
                    Exit For
                End If
            Next
            If isprime = True Then     ' Prime found
    
            End If
    
            
    
        End Function
    
    End Class



    Quote Originally Posted by incidentals View Post
    Code:
    	
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            
         
            Dim str As String ' dont know why you want this
            Dim n As Integer 'variable for the lower value
            Dim m As Integer 'variable for the upper value
    
            Dim TestLimit As String 'type all messed up
            Dim TestPrime As String 'type all messed up
            Dim TestNum As String   'type all messed
    
            Dim x As Integer 'unnecessary as x is a local counter value but good practice
    
            Dim isprime As boolean ' no its the result of a function and it will be a boolean
    
    
            str = "" 'why do you need this
            n = InputBox("Enter lower limit") ' ok lets getvthe first value
            m = InputBox("Enter Upper limit") ' ok lets get the next value
    
                                              ' good thats 2 value done, but no tests yet
                                              ' the actual output of the inboxes will be strings but the typing of n and m will cast them to integers
    
            If (n > 50) Then                  ' this test is inadequate you said n>2 and m<50, why only test >50
                MsgBox("outside range")       'message box should say n too big , still the wrong test though!
                Exit Sub
            End If
    
    '***********************************************************
    ' the 2 tests your spec setout are
    
    if n<2 then 
    msgbox("the lower limit is too small - start again")
    exit sub
    end if
    
    if m>50 then
    msgbox("the upperlimit is too big - start again")
    exit sub
    end if
    
    '***********************************************************
    
            '   
            ' Eliminate even numbers 
            If n Mod 2 = 0 Then n = n + 1 'this ensures your lowerlimit is odd to start from
    
            '   Loop through ODD numbers starting with 3  ' what is the lowerlimit was 23
    
    '***********************************************************
    'junk the loop
    
            TestNum = 3
            TestLimit = TestPrime
            Do While TestLimit > TestNum
                For x = TestNum To TestLimit Step 2
    
                Next
                If TestPrime Mod TestNum = 0 Then
                    '   Uncomment this if you really want to know
                    '   MsgBox "Divisible by " & TestNum   
    
                    Exit Sub
                End If
    
                '   There's logic to this.  Think about it.
                TestLimit = TestPrime \ TestNum
    
                '   Remember, we only bother to check odd numbers
                For x = n To m Step 2
                    'test x here to see if prime
                    'if x is prime with your function isprime() then add to list
    
                    If isprime(x) Then List.additem(x)
                Next
            Loop
    
            '   If we made it through the loop, the number is a prime.
    
            Isprime = True
    
    'end of junk
    '*****************************************************************************
    
    '*****************************************************************************
    'replacement loop 
    
    '   Remember, we only bother to check odd numbers
    
                For x = n To m Step 2                 ' this for does from an odd lowerlimit then +2,+4,+... up to the last odd number before the upperlimit
    
                    'test x here to see if prime
                    'if x is prime with your function isprime() then add to list
    
                    If isprime(x) Then List.additem(x) 'if the result of a new function called isprime is true then store the x that was tested in the listbox
                Next                                   ' loop some more
    
    
       End Sub
    
    
    'now you need to write the prime testing function
    
    I give you a start
    
    public function isprime(arg)as boolean
    
    isprime=false
    
    'do your test loop here
    'return true if arg is indeed prime with isprime=true
    
    end function
    
    End Class
    now its your turn read this remove extraneous stuff

    understand the way it works and then write the isprime function
    and then post it back and we will see where you have got to!

    here to talk

  23. #23
    PowerPoster
    Join Date
    Oct 2008
    Location
    Midwest Region, United States
    Posts
    3,574

    Re: Prime number code

    I don't see you assigning a value to "n" in the IsPrime function.

    Should "n = arg?"

    Or do you want to use "arg - 1" instead of "n - 1?"

  24. #24

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    ahh I have no idea what arg means !! SEriously im really new at this, its like learning a new language and right now Im a newbie


    Quote Originally Posted by vbfbryce View Post
    I don't see you assigning a value to "n" in the IsPrime function.

    Should "n = arg?"

    Or do you want to use "arg - 1" instead of "n - 1?"

  25. #25

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    thanks you guys. oh and by the way I am a girl not a guy

    ok so i think i finally got the "isprime" part correct.. now im still getting errors with the code for adding the primes to the list box. I don't understand what I am suppose to put? ;/ its driving me insane!

    Code:
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
    
            Dim n As Integer 'variable for the lower value
            Dim m As Integer 'variable for the upper value
            Dim TestLimit As Integer 'type all messed up
            Dim TestPrime As Integer 'type all messed up
            Dim TestNum As Integer   'type all messed
            Dim isprime As Boolean ' no its the result of a function and it will be a boolean
    
    
            n = InputBox("Enter lower limit") ' ok lets getvthe first value
            m = InputBox("Enter Upper limit") ' ok lets get the next value
    
            ' good thats 2 value done, but no tests yet
            ' the actual output of the inboxes will be strings but the typing of n and m will cast them to integers
    
    
    
    
            If n < 2 Then
                msgbox("the lower limit is too small - start again")
                Exit Sub
            End If
    
            If m > 50 Then
                msgbox("the upperlimit is too big - start again")
                Exit Sub
            End If
    
    
    
           
            If n Mod 2 = 0 Then n = n + 1 'this ensures your lowerlimit is odd to start from
    
            '   Loop through ODD numbers starting with 3  ' what is the lowerlimit was 23
    
            '***********************************************************
            'junk the loop
    
            TestNum = 3
            TestLimit = TestPrime
            Do While TestLimit > TestNum
                For x = TestNum To TestLimit Step 2
    
                Next
                If TestPrime Mod TestNum = 0 Then
                    Exit Sub
                End If
    
    
                TestLimit = TestPrime \ TestNum
    
                '' to check odd numbers
                For x = n To m Step 2
                    'test x here to see if prime
                    'if x is prime with your function isprime() then add to list
    
                    If isprime(x) Then List.additem(x)
                Next
            Loop
    
            '   If we made it through the loop, the number is a prime.
    
            Isprime = True
    
            'end of junk
            '*****************************************************************************
    
            '*****************************************************************************
            'replacement loop 
    
            '   Remember, we only bother to check odd numbers
    
            For x = n To m Step 2                 ' this for does from an odd lowerlimit then +2,+4,+... up to the last odd number before the upperlimit
    
             
             
            Next
                If isprime(x) Then List.additem(x) 'if the result of a new function called isprime is true then store the x that was tested in the listbox
            ' loop some more
            
    
        End Sub
    
        Public Function isprime(ByVal arg) As Boolean
            Dim n As Integer
    
            Dim ReturnValue As Boolean = True
            For F = 2 To n
                If n Mod F = 0 Then
                    ReturnValue = False
                    Exit For
                End If
            Next
            Return ReturnValue
        End Function
    
    
    
    End Class
    Quote Originally Posted by akhileshbc View Post
    No need to be ashamed of anything. Just follow some some good tutorials, understand it, try it out(in VB)... errors may pop out in some cases.. try to figure out what it says... try to solve it... if not successful, post it here... we'll help you..

    Quote Originally Posted by incidentals View Post
    agreed

    he is trying and thats what counts

    some people come exspecting to be given the answers

    apparently having done nothing but asked

    here to talk

  26. #26
    PowerPoster kaliman79912's Avatar
    Join Date
    Jan 2009
    Location
    Ciudad Juarez, Chihuahua. Mexico
    Posts
    2,593

    Re: Prime number code

    Hello, I am posting a totally new solution. I did not use previous post's code. This has some advantages I will describe

    vb.net Code:
    1. 'Find Prime Numbers
    2.  
    3.     Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
    4.         Dim N As Integer
    5.         Dim M As Integer
    6.         Dim isPrime As Boolean
    7.  
    8.         N = (CInt(txtLower.Text) \ 2) * 2 + 1
    9.         M = CInt(txtUpper.Text)
    10.         If N < 2 Then N = 3
    11.  
    12.         lstPrimes.Items.Clear()
    13.  
    14.         For i = N To M Step 2
    15.             isPrime = True
    16.             For j = 0 To lstPrimes.Items.Count - 1
    17.                 If i Mod lstPrimes.Items(j) = 0 Then
    18.                     isPrime = False
    19.                     Exit For
    20.                 End If
    21.             Next
    22.             If isPrime Then lstPrimes.Items.Add(i)
    23.         Next
    24.  
    25.     End Sub

    First. Instead of inputboxes I used a couple of textBoxes named txtLower and txtUpper, and a button (btnGo) that starts the process.

    the formula (CInt(txtLower.Text) \ 2) * 2 + 1 makes sure your number is an odd integer. That is not necesary for the upper limit.

    I did not put a limit on the upper value as you can find primes for any range, but can't start before 2 as 1 may mess things up. The first prime is 2 so there is no need for the message when the lower is less than 2, just start at 2

    The interesting thing in this loop is that it does not test against all available numbers but just against found primes, as there is no need to test for other numbers because all of them are multiples of primes. This makes the loop more efficient. Also, if an exact division is found, the for stops and continues with next value.

    i Mod lstPrimes.Items(j) is enaugh to see if it can be divided exactly.

    This code does not test against Alpha input so it can mess the process, but as a case study it does what it needs to do.
    Last edited by kaliman79912; Dec 22nd, 2011 at 04:32 PM.
    More important than the will to succeed, is the will to prepare for success.

    Please rate the posts, your comments are the fuel to keep helping people

  27. #27
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Prime number code

    you still have not fixed the main sub routine

    and the test function is being called outwide the loop

    we will enevtually get rid of the junk
    and end up with a cleaner piece of code

    the problem her that too many people are making odd ( unfortunately not helpful comments)

    the word arg is in the brackets of the declaration of the function isprime()

    so it is a value passed to the function and used within it to do what ever task you have specified!

    when we call the function isprime(arg) we use the variable that we want to test
    in your case the variable is the X thing from the loop

    we want to test x to see if it is a prime
    the test is exhaustive as the definition of a prime is a value that can be devided by itsself and 1 only!

    so lets look at you atempt at ISPRIME()

    Code:
    Public Function isprime(ByVal arg) As Boolean
            Dim n As Integer ' why have you introduced n here - do you think it is the upperlimit
                                   ' if we needed it I would have suggested passing more than one argument
    
            Dim ReturnValue As Boolean = True ' what is the purpose of this declaration - is it to allow us to  pass the answer back?
                                                           ' answers (returned values) are returned in the name of the function
                                                           ' so when we are ready the result will be isprime=<something>
    
            For F = 2 To n  ' ok so now your cooking you are about to test from 2 to n the upper limit
                                 ' whoops this function was never passed the upper limit
                                 ' why would you pass 50 to test and see if lets say 9 was a prime number?
                
            If n Mod F = 0 Then ' right a test , good thinking, but what are you testing?
                                        ' i see its that fictitious upperlimit again ( aargh!)
    
                    ReturnValue = False 'yup thats the right output, but in the wrong place
                                                'we don't have a function called returnvalue
                                                'its called ISPRIME
                    Exit For                  'and yes cancel any more test once devisable it cannot be prime
                End If
            Next
            Return ReturnValue 'this is not need as you will have already filled the variable with the result
                                       'the function is waiting to end
        End Function
    my comments are true for the vast number of languages that support function, true some of them use return <something> to send back the result, but vb does not ( although i'm not sure about .net)

    anyway...

    good attempt now lets fix it

    Code:
    Public Function isprime(ByVal arg) As Boolean
    
            isprime = True        ' the default state, all numbers are prime unless they are not
                                       ' no need for "if else"
            For F = 2 To arg-1  ' arg is the value you want to test we know it devides itself
                                       ' can anything smaller devide it
    
                If arg Mod F = 0 Then ' if a lesser value can devide it
                    isprime = False   'set the return value to false (this arg is not a prime)
                    Exit for ' you might be able to "exit function" here as well i cant test iam on wrong machine!
                End If
            Next            ' get the next smaller value to test arg with
      
        ' the isprime return value was set true to start and false when arg was devisable
        End Function
    hope that makes more sense
    now for the final bit cleaning up the main sub

    Code:
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
    
            Dim n As Integer 'variable for the lower value
            Dim m As Integer 'variable for the upper value
        
    
            n = InputBox("Enter lower limit") ' ok lets getvthe first value
            m = InputBox("Enter Upper limit") ' ok lets get the next value
    
            ' good thats 2 value done, but no tests yet
    
            ' the actual output of the inboxes will be strings but the typing of n and m will cast them to integers
    
            If n < 2 Then
                msgbox("the lower limit is too small - start again")
                Exit Sub
            End If
    
            If m > 50 Then
                msgbox("the upperlimit is too big - start again")
                Exit Sub
            End If
    
            If n Mod 2 = 0 Then n = n + 1 'this ensures your lowerlimit is odd to start from
    
            'replacement loop 
    
            '   Remember, we only bother to check odd numbers
    
            For x = n To m Step 2                 ' this for does from an odd lowerlimit then +2,+4,+... up to the last odd number before the upperlimit
    
             
                      If isprime(x) Then List.additem(x) 'if the result of a new function called isprime is true then store the x that was tested in the listbox
       
            Next
            ' loop some more
            
    
        End Sub
    
    'put isprime() function definition here
    
    End Class
    now is that crystal clear now

    you may have to fix syntax
    i am writting this in text only
    dont have a mcchine here to try anything on

    sorry

    hope this has helped

    please rate this and my other posts if the have helped

    ask even if there is the tiniest bit you don't understand

    nice to see your a girly programmer

    sorry if the he hurt but its english for you dont know the gender

    here to talk

  28. #28
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Prime number code

    kaliman

    she is having enough problems with her code in terms of understanding

    and while you code is fine, it does not address her absolute criterior

    and you introduce even more complexity ( looks simpler but is more difficult to full appreciate at her level

    maybe she can come back to it with a little more understanding

    here to talk

  29. #29
    PowerPoster kaliman79912's Avatar
    Join Date
    Jan 2009
    Location
    Ciudad Juarez, Chihuahua. Mexico
    Posts
    2,593

    Re: Prime number code

    My bad. The code I posted fails if you put a lower limit higher than 2 because it does not check for the first primes. Working on that, will post in a few minutes. Will try to make it again without advanced logic.
    More important than the will to succeed, is the will to prepare for success.

    Please rate the posts, your comments are the fuel to keep helping people

  30. #30
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Prime number code

    once all of the coments are removed it looks way simpler

    but with out the comments it is just and solution with no

    knowledge transfer

    here to talk

  31. #31
    PowerPoster kaliman79912's Avatar
    Join Date
    Jan 2009
    Location
    Ciudad Juarez, Chihuahua. Mexico
    Posts
    2,593

    Re: Prime number code

    Here is a working, simpler code (simpler than my previous one). As Insidentals says, this may be a little bit more advanced, but I think it is clear. Look into it, you may find it helpfull

    vb.net Code:
    1. 'Find primes
    2.  
    3.     Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
    4.         Dim N As Integer 'Lower Limit
    5.         Dim M As Integer 'Upper Limit
    6.         Dim isPrime As Boolean 'Flag to check if it is prime
    7.  
    8.         'Clear the list for a new set
    9.         lstPrimes.Items.Clear()
    10.  
    11.         'Input both limits
    12.         N = InputBox("Enter Lower limit")
    13.         M = InputBox("Enter Upper Limit")
    14.  
    15.         'The first prime is 2, the only pair, so if the user inputs 2 or less
    16.         'on the lower limit then add the 2 to the list and set the limit to 3
    17.         'to star testing from there
    18.         If N < 3 Then
    19.             lstPrimes.Items.Add(2)
    20.             N = 3
    21.         End If
    22.  
    23.         'Make sure N is an odd number.
    24.         If N Mod 2 = 0 Then N += 1
    25.  
    26.         'i would be the tested number, only odd (step 2)
    27.         For i = N To M Step 2
    28.             'Start with the assumption that the number is prime
    29.             isPrime = True
    30.             'j will be the divisor. There is never a need to test against a number
    31.             'higher than half the value (i/2), and only odd numbers (step 2)
    32.             For j = 3 To i / 2 Step 2
    33.                 'If the module (residual) is 0, then it can be exactly divided
    34.                 If i Mod j = 0 Then
    35.                     'If it can be divided then it is not prime
    36.                     isPrime = False
    37.                     'If you know it is not a prime, no need to test the rest of divisors
    38.                     Exit For
    39.                 End If
    40.             Next j
    41.             'If its a prime add it to the list
    42.             If isPrime Then lstPrimes.Items.Add(i)
    43.         Next i
    44.  
    45.     End Sub
    Last edited by kaliman79912; Dec 22nd, 2011 at 05:05 PM.
    More important than the will to succeed, is the will to prepare for success.

    Please rate the posts, your comments are the fuel to keep helping people

  32. #32
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Prime number code

    Kaliman makes and observation that i had missed

    he is correctly states that the test does not need to go right upto the value being tested

    but instead only half way

    so function isprime can work much faster ( potentially twice as fast ) if we change the limits of the test loop

    and the divisible by 2 doenot need to be tested as the candidates are all odd

    so

    For F = 2 To arg-1 ' arg is the value you want to test we know it devides itself
    ' can anything smaller devide it


    'becomes

    For F = 3 To arg/2 ' arg is the value you want to test we know it devides itself
    ' can anything half its size or less devide it

    this is looking better all the time

    here to talk
    Last edited by incidentals; Dec 22nd, 2011 at 05:07 PM.

  33. #33
    PowerPoster kaliman79912's Avatar
    Join Date
    Jan 2009
    Location
    Ciudad Juarez, Chihuahua. Mexico
    Posts
    2,593

    Re: Prime number code

    Quote Originally Posted by incidentals View Post
    Kaliman makes and observation that i had missed

    he is correctly states that the test does not need to go right upto the value being tested

    but instead only half way

    so function isprime can work much faster ( potentially twice as fast ) if we change the limits of the test loop

    so

    For F = 2 To arg-1 ' arg is the value you want to test we know it devides itself
    ' can anything smaller devide it


    'becomes

    For F = 2 To arg/2 ' arg is the value you want to test we know it devides itself
    ' can anything half its size or less devide it

    this is looking better all the time

    here to talk
    Since you are not testing even numbers it is not necesary to test VS 2 either. So your loop should be

    For F = 3 to arg/2
    More important than the will to succeed, is the will to prepare for success.

    Please rate the posts, your comments are the fuel to keep helping people

  34. #34
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Prime number code

    there is nothing wrong with putting the whole problem into a single sub routine as kaliman does

    but it is good practice to create functions that you can use again in other solutions

    and for the newbies it is good to understand a little more about the programming world they have entered

    here to talk

  35. #35
    PowerPoster kaliman79912's Avatar
    Join Date
    Jan 2009
    Location
    Ciudad Juarez, Chihuahua. Mexico
    Posts
    2,593

    Re: Prime number code

    Quote Originally Posted by incidentals View Post
    there is nothing wrong with putting the whole problem into a single sub routine as kaliman does

    but it is good practice to create functions that you can use again in other solutions

    and for the newbies it is good to understand a little more about the programming world they have entered

    here to talk
    I totally agree, that is the principle of a good structured program. This may be a simple algorithm, but you should try to structure procedures and functions as Incidentals suggests.
    More important than the will to succeed, is the will to prepare for success.

    Please rate the posts, your comments are the fuel to keep helping people

  36. #36

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    Thank you sooo much for helping me out.
    NOW A NEW ERROR POPS UP! when i start debugging it gives me this and says that the method or operation is not implemented. what is that suppose to mean? :


    Class List

    Shared Sub additem(ByVal x As Object)
    Throw New NotImplementedException
    End Sub

    End Class




    Quote Originally Posted by incidentals View Post
    you still have not fixed the main sub routine

    and the test function is being called outwide the loop

    we will enevtually get rid of the junk
    and end up with a cleaner piece of code

    the problem her that too many people are making odd ( unfortunately not helpful comments)

    the word arg is in the brackets of the declaration of the function isprime()

    so it is a value passed to the function and used within it to do what ever task you have specified!

    when we call the function isprime(arg) we use the variable that we want to test
    in your case the variable is the X thing from the loop

    we want to test x to see if it is a prime
    the test is exhaustive as the definition of a prime is a value that can be devided by itsself and 1 only!

    so lets look at you atempt at ISPRIME()

    Code:
    Public Function isprime(ByVal arg) As Boolean
            Dim n As Integer ' why have you introduced n here - do you think it is the upperlimit
                                   ' if we needed it I would have suggested passing more than one argument
    
            Dim ReturnValue As Boolean = True ' what is the purpose of this declaration - is it to allow us to  pass the answer back?
                                                           ' answers (returned values) are returned in the name of the function
                                                           ' so when we are ready the result will be isprime=<something>
    
            For F = 2 To n  ' ok so now your cooking you are about to test from 2 to n the upper limit
                                 ' whoops this function was never passed the upper limit
                                 ' why would you pass 50 to test and see if lets say 9 was a prime number?
                
            If n Mod F = 0 Then ' right a test , good thinking, but what are you testing?
                                        ' i see its that fictitious upperlimit again ( aargh!)
    
                    ReturnValue = False 'yup thats the right output, but in the wrong place
                                                'we don't have a function called returnvalue
                                                'its called ISPRIME
                    Exit For                  'and yes cancel any more test once devisable it cannot be prime
                End If
            Next
            Return ReturnValue 'this is not need as you will have already filled the variable with the result
                                       'the function is waiting to end
        End Function
    my comments are true for the vast number of languages that support function, true some of them use return <something> to send back the result, but vb does not ( although i'm not sure about .net)

    anyway...

    good attempt now lets fix it

    Code:
    Public Function isprime(ByVal arg) As Boolean
    
            isprime = True        ' the default state, all numbers are prime unless they are not
                                       ' no need for "if else"
            For F = 2 To arg-1  ' arg is the value you want to test we know it devides itself
                                       ' can anything smaller devide it
    
                If arg Mod F = 0 Then ' if a lesser value can devide it
                    isprime = False   'set the return value to false (this arg is not a prime)
                    Exit for ' you might be able to "exit function" here as well i cant test iam on wrong machine!
                End If
            Next            ' get the next smaller value to test arg with
      
        ' the isprime return value was set true to start and false when arg was devisable
        End Function
    hope that makes more sense
    now for the final bit cleaning up the main sub

    Code:
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
    
            Dim n As Integer 'variable for the lower value
            Dim m As Integer 'variable for the upper value
        
    
            n = InputBox("Enter lower limit") ' ok lets getvthe first value
            m = InputBox("Enter Upper limit") ' ok lets get the next value
    
            ' good thats 2 value done, but no tests yet
    
            ' the actual output of the inboxes will be strings but the typing of n and m will cast them to integers
    
            If n < 2 Then
                msgbox("the lower limit is too small - start again")
                Exit Sub
            End If
    
            If m > 50 Then
                msgbox("the upperlimit is too big - start again")
                Exit Sub
            End If
    
            If n Mod 2 = 0 Then n = n + 1 'this ensures your lowerlimit is odd to start from
    
            'replacement loop 
    
            '   Remember, we only bother to check odd numbers
    
            For x = n To m Step 2                 ' this for does from an odd lowerlimit then +2,+4,+... up to the last odd number before the upperlimit
    
             
                      If isprime(x) Then List.additem(x) 'if the result of a new function called isprime is true then store the x that was tested in the listbox
       
            Next
            ' loop some more
            
    
        End Sub
    
    'put isprime() function definition here
    
    End Class
    now is that crystal clear now

    you may have to fix syntax
    i am writting this in text only
    dont have a mcchine here to try anything on

    sorry

    hope this has helped

    please rate this and my other posts if the have helped

    ask even if there is the tiniest bit you don't understand

    nice to see your a girly programmer

    sorry if the he hurt but its english for you dont know the gender

    here to talk

  37. #37

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    This works!! and I actually understand what you were doing in each step. THANK YOU! thank you for the explanation, you guys are so helpful and patient.. what a great forum



    Quote Originally Posted by kaliman79912 View Post
    Here is a working, simpler code (simpler than my previous one). As Insidentals says, this may be a little bit more advanced, but I think it is clear. Look into it, you may find it helpfull

    vb.net Code:
    1. 'Find primes
    2.  
    3.     Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
    4.         Dim N As Integer 'Lower Limit
    5.         Dim M As Integer 'Upper Limit
    6.         Dim isPrime As Boolean 'Flag to check if it is prime
    7.  
    8.         'Clear the list for a new set
    9.         lstPrimes.Items.Clear()
    10.  
    11.         'Input both limits
    12.         N = InputBox("Enter Lower limit")
    13.         M = InputBox("Enter Upper Limit")
    14.  
    15.         'The first prime is 2, the only pair, so if the user inputs 2 or less
    16.         'on the lower limit then add the 2 to the list and set the limit to 3
    17.         'to star testing from there
    18.         If N < 3 Then
    19.             lstPrimes.Items.Add(2)
    20.             N = 3
    21.         End If
    22.  
    23.         'Make sure N is an odd number.
    24.         If N Mod 2 = 0 Then N += 1
    25.  
    26.         'i would be the tested number, only odd (step 2)
    27.         For i = N To M Step 2
    28.             'Start with the assumption that the number is prime
    29.             isPrime = True
    30.             'j will be the divisor. There is never a need to test against a number
    31.             'higher than half the value (i/2), and only odd numbers (step 2)
    32.             For j = 3 To i / 2 Step 2
    33.                 'If the module (residual) is 0, then it can be exactly divided
    34.                 If i Mod j = 0 Then
    35.                     'If it can be divided then it is not prime
    36.                     isPrime = False
    37.                     'If you know it is not a prime, no need to test the rest of divisors
    38.                     Exit For
    39.                 End If
    40.             Next j
    41.             'If its a prime add it to the list
    42.             If isPrime Then lstPrimes.Items.Add(i)
    43.         Next i
    44.  
    45.     End Sub

  38. #38

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    I will keep this in mind. I am so pleased with your help. Thanks a bunch.


    Quote Originally Posted by incidentals View Post
    there is nothing wrong with putting the whole problem into a single sub routine as kaliman does

    but it is good practice to create functions that you can use again in other solutions

    and for the newbies it is good to understand a little more about the programming world they have entered

    here to talk

  39. #39
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Prime number code

    glad she has got it

    didn't we do well

    the problem with my code is its for vb6 not net

    so
    listbox.additem x
    is now
    listbox.items.add x

    oh well

    btw kaliman the mod operator is the modulus (the remainder due to whole number division) not the module

    I have this need to teach... sorry

    now if she would just remember to rate out posts

    here to talk

  40. #40

    Thread Starter
    Member
    Join Date
    Dec 2011
    Posts
    35

    Re: Prime number code

    hahaha yes thanks so much for sticking with me through this journey of mine incidentals i rated all your guys posts, with good ratings of course i have even harder programs to make starting tomorrow. I know I will need more help.



    Quote Originally Posted by incidentals View Post
    glad she has got it

    didn't we do well

    the problem with my code is its for vb6 not net

    so
    listbox.additem x
    is now
    listbox.items.add x

    oh well

    btw kaliman the mod operator is the modulus (the remainder due to whole number division) not the module

    I have this need to teach... sorry

    now if she would just remember to rate out posts

    here to talk

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width