Prime number checker returns the same result each time - ios

I'm a beginner programmer learning Swift and made a basic prime number checker. No matter what it will only give one result, instead of changing based on wether or not the number is prime. Any help would be appreciated.
#IBAction func primeCheck(sender: AnyObject) {
var numberInt = number.text.toInt()
var isPrime = true
if number != nil {
if numberInt == 1 {
isPrime = false
}
if numberInt != 1 {
for var i = 2; i < numberInt; i++ {
if numberInt! % i == 0 {
isPrime = false
} else {
isPrime = true
}
}
}
}
if isPrime == true {
result.text = "\(numberInt!) is a prime number!"
} else {
result.text = "\(numberInt!) is not a prime number!"
}
}

I have another possible solution. At first I divide by two because it cannot be a prime number. Then you loop until the number is prime or the number divided by two is less than the divider.
#IBAction func primeCheck(sender: AnyObject) {
var numberInt = number.text.toInt()
var isPrime = true
var divider = 3
if number < 2 || (number != 2 && number % 2 == 0) {
isPrime = false
}
// you only have to check to half of the number
while(isPrime == true && divider < number / 2){
isPrime = number % divider != 0
divider += 2
}
if isPrime == true {
result.text = "\(numberInt!) is a prime number!"
} else {
result.text = "\(numberInt!) is not a prime number!"
}
}

The error in your logic comes in this section:
if numberInt! % i == 0 {
isPrime = false
} else {
isPrime = true
}
At the top of your function, you initialize isPrime to be true, so in your loop you only need to look for cases that prove the number is not prime. You don't ever need to set isPrime = true again, so just drop the else condition:
if numberInt! % i == 0 {
isPrime = false
}

You actually have two functions here. One to check if a number is prime and the other to display the result. Separating these makes everything much easier to manage.
// function to check primality and return a bool
// note that this can only accept a non optional Int so there is
// no need to check whether it is valid etc...
func checkNumberIsPrime(number: Int) -> Bool {
// get rid of trivial examples to improve the speed later
if number == 2 || number == 3 {
return true
}
if number <= 1 || number%2 == 0 {
return false
}
// square root and round up to the nearest int
let squareRoot: Int = Int(ceil(sqrtf(Float(number))))
// no need to check anything above sqrt of number
// any factor above the square root will have a cofactor
// below the square root.
// don't need to check even numbers because we already checked for 2
// half the numbers checked = twice as fast :-D
for i in stride(from: 3, to: squareRoot, by: 2) {
if number % i == 0 {
return false
}
}
return true
}
// function on the button. Run the check and display results.
#IBAction func primeCheck(sender: AnyObject) {
let numberInt? = numberTextField.text.toInt() // don't call a text field "number", it's just confusing.
if let actualNumber = numberInt {
if checkNumberIsPrime(actualNumber) {
resultLabel.text = "\(actualNumber) is a prime number!" // don't call a label "result" call it "resultLabel". Don't confuse things.
} else {
resultLabel.text = "\(actualNumber) is not a prime number!"
}
} else {
resultLabel.text = "'\(numberTextField.text)' is not a number!"
}
}
It makes it all much easy to read and maintain.

You have to break out of the loop after you find that the number is divisble by another number. Also for prime check you only have to check the divisibility till the square root of the number.
You can also use optional binding to extract numberInt and check for nil. That's the swift way.
#IBAction func primeCheck(sender: AnyObject) {
var isPrime = true
if let numberInt = number.text.toInt() {
if numberInt == 1 {
isPrime = false /
}
else // Add else because you dont have to execute code below if number is 1
{
if numberInt != 1 {
for var i = 2; i * i <= numberInt; i++ { // Only check till squareroot
if numberInt % i == 0 {
isPrime = false
break // Break out of loop if number is divisible.
} // Don't need else condition because isPrime is initialised as true.
}
}
}
if isPrime {
result.text = "\(numberInt) is a prime number!"
} else {
result.text = "\(numberInt) is not a prime number!"
}
}
}
Reason for square root check : Why do we check up to the square root of a prime number to determine if it is prime?
You can refine the code further by refactoring the prime check into a separate function.
func isPrime(number:Int) -> Bool
{
if number == 1 {
return false
}
else
{
if number != 1 {
for var i = 2; i * i <= numberInt; i++ {
if numberInt % i == 0 {
return false
}
}
}
}
return true
}
#IBAction func primeCheck(sender: AnyObject) {
if let numberInt = number.text.toInt() {
if isPrime(numberInt) {
result.text = "\(numberInt) is a prime number!"
} else {
result.text = "\(numberInt) is not a prime number!"
}
}
}

Well i don't know about swift, but maybe this is wrecking your code:
if numberInt! <<
To do a faster algorithm you could just search for divisors from 2 to sqrt(numberInt). (Theorem)

Related

Generate consecutive and same number on Array effectively in Swift

I have an example of a case in the application to create a numeric pin pattern that should not have a consecutive number and the same number of all.
Examples of PIN patterns that are rejected are as follows:
123456,
234567,
345678,
654321,
765432,
876543,
000000 and other similar PIN patterns.
var rejectedPinList: [[Int]] = [[Int]]()
var consecutiveNumber = [0,1,2,3,4,5,6,7,8,9,0]
func incrementNumber(currentIndex: Int) -> [Int] {
var rejectedPinPattern: [Int] = [Int]()
for currentIndex in stride(from: currentIndex, to: currentIndex+6, by: 1){
rejectedPinPattern.append(consecutiveNumber[currentIndex])
}
return rejectedPinPattern
}
func decrementNumber(currentIndex: Int) -> [Int] {
var rejectedPinPattern: [Int] = [Int]()
for currentIndex in stride(from: currentIndex, to: currentIndex-6, by: -1){
rejectedPinPattern.append(consecutiveNumber[currentIndex])
}
return rejectedPinPattern
}
func constantNumber(currentIndex: Int) -> [Int] {
var rejectedPinPattern: [Int] = [Int]()
for _ in currentIndex...currentIndex+6 {
rejectedPinPattern.append(consecutiveNumber[currentIndex])
}
return rejectedPinPattern
}
for number in consecutiveNumber {
rejectedPinList.append(constantNumber(currentIndex: number))
if number < 5 {
rejectedPinList.append(incrementNumber(currentIndex: number))
} else if number > 5 {
rejectedPinList.append(decrementNumber(currentIndex: number))
} else {
rejectedPinList.append(incrementNumber(currentIndex: number))
rejectedPinList.append(decrementNumber(currentIndex: number))
}
}
func inputPin(pin: [Int]) {
if rejectedPinList.contains(pin) {
print("Pin Rejected!")
} else {
}
}
inputPin(pin: [8,7,6,5,4,3]) // Should be Rejected!
What I'm looking for is to be more effective than the algorithm code I made above in generating consecutive & same numbers. Because in my opinion, the code I made is too long and not very effective and may be wasteful. Thank you!
Instead of computing a list of all invalid pins in advance, you can verify the given pin by computing the set of all differences of adjacent digits. A pin is invalid if the set consists of -1, 0, or +1 only:
func validatePIN(_ pin: [Int]) -> Bool {
if pin.isEmpty { return false }
let diffs = Set(zip(pin, pin.dropFirst()).map(-))
return diffs.count != 1 || abs(diffs.first!) > 1
}
As the question was to improve efficiency, the approach below this implements the some initial checks before it starts looping through the array to minimise the total number of iterations/time.
func validatePin(_ pin: [Int], minLength: Int = 2 ) -> Bool {
guard pin.count >= max(minLength, 2) else {return false}
guard Set(pin).count != 1 else {return false} //all the same
guard abs(pin.first! - pin.last!) == pin.count - 1 else {return true} //can't be a sequence
let delta = pin.first! < pin.last! ? -1 : 1
for index in (0...pin.count - 2) {
if pin[index] - pin[index + 1] != delta {return true} //items not sequential
}
return false //items are sequential
}
I think this should do what you want. It checks to see if there are any consecutive digits that have an absolute difference that isn't 1. If so then the PIN may be valid (pending a check for repeated digits).
To check for repeated digits, the digits are added to an NSCountedSet. If the count for any digit is the same as the number of digits then the PIN is invalid.
func validatePIN(_ candidate: [Int]) -> Bool {
guard !candidate.isEmpty else {
return false
}
let digitSet = NSCountedSet()
var possiblyValid = false
var lastSign: Int?
for i in 0..<candidate.count {
digitSet.add(candidate[i])
if i > 0 && !possiblyValid {
let difference = candidate[i]-candidate[i-1]
let thisSign = difference.signum()
if abs(difference) != 1 {
possiblyValid = true
} else if let sign = lastSign, sign != thisSign {
possiblyValid = true
}
lastSign = thisSign
}
}
for digit in digitSet {
if digitSet.count(for: digit) == candidate.count {
return false
}
}
return possiblyValid
}
print(validatePIN([]))
print(validatePIN([8,7,6,5,3,3]))
print(validatePIN([8,7,6,5,4,3]))
print(validatePIN([2,2,2,2,2,2]))
print(validatePIN([1,2,3,4,3,2]))
gives:
false
true
false
false
true
You could also add a test for minimum length in the guard statement
Thank you all for helping me. I also improvise my algorithm. Here's my code:
func validatePIN(_ pin: [Int]) -> Bool {
if (pin.isEmpty == true) ||
(pin[0] < 5 && pin == Array(pin[0]...pin[0]+5)) ||
(pin[0] > 5 && pin == Array(stride(from: pin[0], through: pin[0]-5, by: -1)) ||
(pin.allSatisfy({ $0 == pin[0] }))) { return false }; return true
}

Error when add negative numbers in calculator

I have this code:
class MainViewController: UIViewController {
#IBOutlet weak var summaryLbl: UILabel!
var actualNumber: Double = 0
var previousNumber: Double = 0
var operationMath: Bool = false
var operation = 0
#IBAction func numberPressed(_ sender: UIButton) {
if operationMath == true {
summaryLbl.text = String(sender.tag)
actualNumber = Double(summaryLbl.text!)!
operationMath = false
} else {
if summaryLbl.text == "0" {
summaryLbl.text = ""
}
summaryLbl.text = summaryLbl.text! + String(sender.tag)
actualNumber = Double(summaryLbl.text!)!
}
}
#IBAction func buttons(_ sender: UIButton) {
if summaryLbl.text != "" && sender.tag != 10 && sender.tag != 17 {
previousNumber = Double(summaryLbl.text!)!
if sender.tag == 13 {
summaryLbl.text = "/"
} else if sender.tag == 14 {
summaryLbl.text = "x"
} else if sender.tag == 15 {
summaryLbl.text = "-"
} else if sender.tag == 16 {
summaryLbl.text = "+"
} else if sender.tag == 11 {
var number: Double = Double(summaryLbl.text!)!
number.negate()
let rounded = number.rounded()
summaryLbl.text = String(rounded).replacingOccurrences(of: ".0", with: "", options: .literal, range: nil)
}
operation = sender.tag
operationMath = true
} else if sender.tag == 17 {
var result: Double = 0
var rounded: Double = 0
if operation == 13 {
result = previousNumber / actualNumber
} else if operation == 14 {
result = previousNumber * actualNumber
} else if operation == 15 {
result = previousNumber - actualNumber
} else if operation == 16 {
result = previousNumber + actualNumber
} else if operation == 12 {
result = previousNumber.truncatingRemainder(dividingBy: actualNumber)
}
rounded = result.rounded()
if (result == rounded) {
summaryLbl.text = String(result).replacingOccurrences(of: ".0", with: "", options: .literal, range: nil)
} else {
summaryLbl.text = String(result)
}
} else if sender.tag == 10 {
summaryLbl.text = "0"
previousNumber = 0
actualNumber = 0
operation = 0
}
}
override func viewDidLoad() {
super.viewDidLoad()
summaryLbl.text = "0"
previousNumber = 0
actualNumber = 0
operation = 0
}
}
This is simple calculator.
I have a problem with calculations.
When I click the buttons, for example: 2 + 5 * -
then the application turns off with an error. When I enter such a key combination: 2 + 5 =
This calculation will be done correctly.
 
How do I add commas to numbers?
Does anyone know how to fix the above problems?
A calculator is a Finite State Machine. It can be very complex but in its simplest form it resembles this:
So if we keep things simple and take the above machine as our target, after 2 + 5, our machine expects equals(=) to calculate the result or if an operator is added (like * in our case) it will expect a digit next. giving an operator (minus in our case) will result in an error.
The complexity is limited only by your imagination. You can add support for decimal point numbers, brackets, powers etc. The more sugar you want to add the more complex the FSM will become.
I suggest starting with the simplest one. Maintain your states, the transitions allowed next and error handling in case of wrong transition.
Check this repo on github for Finite State Machine in swift: https://github.com/vishalvshekkar/SwiftFSM
And the corresponding article:
https://blog.vishalvshekkar.com/finite-state-machine-in-swift-ba0958bca34f

UISegmentedControl and .selectedSegmentIndex wrong values?

I have a simple Segment in my code with 3 elements. For testing purposes I also do have a variable that increments based on which of the segments I press (3). The value of that variable is printed in a UITextView. This is the code:
import UIKit
class ViewController: UIViewController
{
#IBOutlet weak var segment: UISegmentedControl!
#IBOutlet weak var prwtoView: UIView!
#IBOutlet weak var prwtoText: UITextField!
var i : Int = 0
override func viewWillAppear(animated: Bool)
{
prwtoText.backgroundColor = UIColor.purpleColor()
prwtoText.textColor = UIColor.whiteColor()
segment.setTitle("Zero", forSegmentAtIndex: 0)
segment.addTarget(self, action: "action", forControlEvents: .ValueChanged)
segment.insertSegmentWithTitle("random", atIndex: 2, animated: false)
}
func action()
{
let argumentForSegment = segment.selectedSegmentIndex
if argumentForSegment == 0
{
i = 0
}
if argumentForSegment == 1
{
i += 2
}
else
{
i += Int(arc4random_uniform(100))
}
print(argumentForSegment)
prwtoText.text = "\(i)"
}
}
While I know that it starts with value -1 i don't want my app to do anything if not pressed. The thing is that even when I press the first segment (0) and it is supposed to make i = 0 it doesn't do that, although if I print argumentForSegment in my terminal it does show the 0 as value. Concluding, every time I press the zero segment (0), my i value won't become 0. Perhaps I am using the wrong method from UISegmentedControl?
edit: Got it fixed by changing the following code:
func action()
{
let argumentForSegment = segment.selectedSegmentIndex
if argumentForSegment == 0
{
i = 0
}
if argumentForSegment == 1
{
i += 2
}
else
{
i += Int(arc4random_uniform(100))
}
print(argumentForSegment)
prwtoText.text = "\(i)"
}
to:
func action()
{
let argumentForSegment = segment.selectedSegmentIndex
if argumentForSegment == 0
{
i = 0
}
if argumentForSegment == 1
{
i += 2
}
else if argumentForSegment == 2 // <==== here
{
i += Int(arc4random_uniform(100))
}
print(argumentForSegment)
prwtoText.text = "\(i)"
}
Could someone explain why it used the priority of else although the value was zero when printing argumentForSegment? In other words why when I had an else alone for the value of argumentForSegment == 0 it chose the else instead of the first statement?
Could someone explain why it used the priority of else although the
value was zero when printing argumentForSegment? In other words why
when I had an else alone for the value of argumentForSegment == 0 it
chose the else instead of the first statement?
When you have a situation where the code is not behaving as you expect, it is helpful to step through it in the debugger, or add some diagnostic print statements.
For example:
func action()
{
let argumentForSegment = segment.selectedSegmentIndex
if argumentForSegment == 0
{
print("In first block")
i = 0
}
if argumentForSegment == 1
{
print("In second block")
i += 2
}
else
{
print("In third block")
i += Int(arc4random_uniform(100))
}
print(argumentForSegment)
prwtoText.text = "\(i)"
}
If you do this, you will notice that when argumentForSegment is 0, the output will be:
In first block
In third block
So, the problem is not that it is choosing the third block over the first. The problem is that it is doing both. You want it to stop after it has detected that argumentForSegment is 0, so add an else to the second conditional statement so that it only does that when the first conditional statement failed:
func action()
{
let argumentForSegment = segment.selectedSegmentIndex
if argumentForSegment == 0
{
i = 0
}
else if argumentForSegment == 1 // added "else" here
{
i += 2
}
else
{
i += Int(arc4random_uniform(100))
}
print(argumentForSegment)
prwtoText.text = "\(i)"
}
To improve on Vacawama's answer, you can format this much easier by using a switch statement:
func action() {
let argumentForSegment = segment.selectedSegmentIndex
switch argumentForSegment {
case 0:
i = 0
case 1:
i += 1
case 2:
i += Int(arc4random_uniform(100))
default:
break
}
print(argumentForSegment)
prwtoText.text = "\(i)"
}
it's much more clean for this type of thing.
(thanks, vacawama)

Stuck in a loop. Very strange because the code sometimes work and sometimes just freezes

I am writing a puzzle game for an IOS. In my code I need to fill an array with some random (and non-random numbers) that will represent the main data structure.
func Random(r : Range<Int>) -> Int {
return Int(arc4random_uniform(UInt32(r.endIndex - r.startIndex))) + r.startIndex
} // function to generate random number
var arrWithColors = [Int]() // array that will hold the numbers
//function to that check if an array contains a number in a range already
func checkForNumberInArrayWithRange(r: Range <Int>, n: Int ) -> Bool {
for i in r.startIndex..<r.endIndex {
if arrWithColors[i] == n { return true }
}
return false
}
// here is the main function where i keep getting stuck. Out of let's say five times it would only work 3 or even less.
func randHexWithTag() {
var rNumber : Int = Random(0...5)
for i in 0...5 {
while (true) {
rNumber = Random(0...5)
if !checkForNumberInArrayWithRange(0...5, n: rNumber) {
break
}
}
arrWithColors[i] = rNumber
}
arrWithColors[10] = arrWithColors[1]
for i in 6...11 {
while(true) {
rNumber = Random(0...5)
if ((rNumber == arrWithColors[0] && i == 9) || (rNumber == arrWithColors[2] && i == 11)) {
continue
}
if !checkForNumberInArrayWithRange(6...11, n: rNumber) {
break
}
}
if (i != 10) {
arrWithColors[i] = rNumber
}
}
arrWithColors[13] = arrWithColors[4]
for i in 12...17 {
while(true) {
rNumber = Random(0...5)
if (rNumber == arrWithColors[3] && i == 12) || (rNumber == arrWithColors[5] && i == 14) {
continue
}
if !checkForNumberInArrayWithRange(12...17, n: rNumber) {
break
}
}
if (i != 13) {
arrWithColors[i] = rNumber
}
}
}
The above code will ALWAYS fail during the first call to checkForNumberInArrayWithRange on this line:
if arrWithColors[i] == n { return true }
That is because arrWithColors is empty, and index i is out of range

Program crashes when integer is not 0, 1 or 2

I am a complete beginner to all things programming, so please forgive any blatant mistakes that you may find. I am writing a program that takes an input number and tells the user whether or not the number is a prime.
#IBOutlet weak var textfield: UITextField!
#IBOutlet weak var label: UILabel!
#IBAction func button(sender: AnyObject) {
if (textfield.text.isEmpty) {
label.text = "Please enter a number!"
} else if (textfield.text == "0" || textfield.text == "1"){
label.text = "The answer is undefined."
textfield.text = nil
} else {
var input = textfield.text.toInt()
if (input! % 2 == 0 && input! != 2) {
label.text = "The number is not prime, one of its divisors is 2."
textfield.text = nil
} else if (input! == 2){
label.text = "The number is indeed prime!"
textfield.text = nil
} else {
var factor = 3
while (factor <= input) {
if (input! % factor == 0 && input! != factor) {
label.text = "The number is not prime, one of its divisors is \(factor)"
} else if (input! % factor != 0){
factor += 2
} else if (input! % factor == 0 && input! == factor) {
label.text = "The number is indeed prime!"
textfield.text = nil
}
}
}
}
}
My code looks like this, but crashes if the input is anything that is not 0, 1, or 2. I know there are better ways to write this program but I just want to figure out what exactly is wrong with this one. Thanks in advance!
In the cases where you are updating the label.text you are not incrementing the factor which leads to an infinite loop. Add a break to those cases to break out of the while loop and all will be well:
while (factor <= input!) {
if (input! % factor == 0 && input! != factor) {
label.text = "The number is not prime, one of its divisors is \(factor)"
break
} else if (input! % factor != 0){
factor += 2
} else if (input! % factor == 0 && input! == factor) {
label.text = "The number is indeed prime!"
textfield.text = nil
break
}
}
It not your swift. It is your programming logic. Your are not crashing, you are hanging in an infinite
loop.
put a println in you while loop.
while (factor <= input) {
println ("Factor (input! % factor)")
Factor 0
Factor 0
Factor 0
Factor 0
You never end up incrementing factor. In my test case I enter 3 as the input.
David
I think the input return a optional variable.
var input = textfield.text.toInt()
//and you force unwrap the input on the this statement:
if (input! % 2 == 0 && input! != 2) {}
I think it crashed on here if the text is not number.
Take a look of the extension of String
extension String {
/// If the string represents an integer that fits into an Int, returns
/// the corresponding integer. This accepts strings that match the regular
/// expression "[-+]?[0-9]+" only.
func toInt() -> Int?
}

Resources