2

I was making a program which could tell if a given number is a prime number or not. No matter whether I enter a prime number or another number, it always shows "it is not a prime number". Is there any fault in it?

10    input "what is the number";a    
20    let b=1    
30    let b=b+1    
40    let k=a/b    
50    let p=fix(k)    
60    if p=k then goto 100    
70    if b<a then goto 30    
80    print "it is a prime number"    
90    goto 110    
100    print "it is not a prime number"    
110    end    
run
Paul R
  • 208,748
  • 37
  • 389
  • 560

2 Answers2

4

Follow the logic:

  1. You enter a number, a.
  2. The program creates b as 1.
  3. The program immediately adds 1 to b, so that b is now 2.
  4. The program sets k to a/b. This means that k is now half of a.
  5. The program sets p to k without the .5 that may or may not be there.
  6. If p (half of a rounded down) is equal to k (half of a not rounded down), that is, if a is divisible by b, it goes to 100 and says it is not a prime number.
  7. Otherwise, if b (which is 2) is less than a the program goes to line 30 and adds another 1 to b and repeats the process, but now b is 3.
  8. Otherwise, if b (which is 2) is equal to a or greater than it, it prints that this is a prime number.

Let's say that the number you enter is 2. Two is, in fact, a prime number. Follow the logic above, however, and you will see that the program will tell us that it is not a prime number, because at step 6, two divided by two is one, and one truncated is still one. The same should be true for any number except 1, because all numbers are divisible by themselves.

My guess is that in your testing, you never tested 1; the program should say that 1 is a prime number (this is because even though 1 is divisible by itself, you start at b=2).

(Note also that this is also technically wrong: one is not a prime number.)

Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30
1

This code describes determining a prime number in basic:

10 INPUT p
20 FOR l = 2 TO INT(SQR(p))
30 LET a = p / l
40 LET b = FIX(a)
50 IF a = b THEN GOTO 80
60 NEXT l
70 PRINT "prime"
80 END
eoredson
  • 1,167
  • 2
  • 14
  • 29