ios how to check if division remainder is integer - iphone

any of you knows how can I check if the division remainder is integer or zero?
if ( integer ( 3/2))

You should use the modulo operator like this
// a,b are ints
if ( a % b == 0) {
// remainder 0
} else
{
// b does not divide a evenly
}

It sounds like what you are looking for is the modulo operator %, which will give you the remainder of an operation.
3 % 2 // yields 1
3 % 1 // yields 0
3 % 4 // yields 1
However, if you want to actually perform the division first, you may need something a bit more complex, such as the following:
//Perform the division, then take the remainder modulo 1, which will
//yield any decimal values, which then you can compare to 0 to determine if it is
//an integer
if((a / b) % 1 > 0))
{
//All non-integer values go here
}
else
{
//All integer values go here
}
Walkthrough
(3 / 2) // yields 1.5
1.5 % 1 // yields 0.5
0.5 > 0 // true

swift 3:
if a.truncatingRemainder(dividingBy: b) == 0 {
//All integer values go here
}else{
//All non-integer values go here
}

You can use the below code to know which type of instance it is.
var val = 3/2
var integerType = Mirror(reflecting: val)
if integerType.subjectType == Int.self {
print("Yes, the value is an integer")
}else{
print("No, the value is not an integer")
}
let me know if the above was useful.

Swift 5
if numberOne.isMultiple(of: numberTwo) { ... }
Swift 4 or less
if numberOne % numberTwo == 0 { ... }

Swift 2.0
print(Int(Float(9) % Float(4))) // result 1

Related

Prime numbers print from range 2...100

I have been assigned with a task to print prime numbers from a range 2...100. I've managed to get most of the prime numbers but can't figure out how to get rid of 9 and 15, basically multiples of 3 and 5. Please give me your suggestion on how can I fix this.
for n in 2...20 {
if n % 2 == 0 && n < 3{
print(n)
} else if n % 2 == 1 {
print(n)
} else if n % 3 == 0 && n > 6 {
}
}
This what it prints so far:
2
3
5
7
9
11
13
15
17
19
One of effective algorithms to find prime numbers is Sieve of Eratosthenes. It is based on idea that you have sorted array of all numbers in given range and you go from the beginning and you remove all numbers after current number divisible by this number which is prime number. You repeat this until you check last element in the array.
There is my algorithm which should do what I described above:
func primes(upTo rangeEndNumber: Int) -> [Int] {
let firstPrime = 2
guard rangeEndNumber >= firstPrime else {
fatalError("End of range has to be greater than or equal to \(firstPrime)!")
}
var numbers = Array(firstPrime...rangeEndNumber)
// Index of current prime in numbers array, at the beginning it is 0 so number is 2
var currentPrimeIndex = 0
// Check if there is any number left which could be prime
while currentPrimeIndex < numbers.count {
// Number at currentPrimeIndex is next prime
let currentPrime = numbers[currentPrimeIndex]
// Create array with numbers after current prime and remove all that are divisible by this prime
var numbersAfterPrime = numbers.suffix(from: currentPrimeIndex + 1)
numbersAfterPrime.removeAll(where: { $0 % currentPrime == 0 })
// Set numbers as current numbers up to current prime + numbers after prime without numbers divisible by current prime
numbers = numbers.prefix(currentPrimeIndex + 1) + Array(numbersAfterPrime)
// Increase index for current prime
currentPrimeIndex += 1
}
return numbers
}
print(primes(upTo: 100)) // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
print(primes(upTo: 2)) // [2]
print(primes(upTo: 1)) // Fatal error: End of range has to be greater than or equal to 2!
what is the Prime num : Prime numbers are the positive integers having only two factors, 1 and the integer itself,
//Funtion Call
findPrimeNumberlist(fromNumber: 1, toNumber: 100)
//You can print any range Prime number using this fucntion.
func findPrimeNumberlist(fromNumber:Int, toNumber: Int)
{
for i in fromNumber...toNumber
{
var isPrime = true
if i <= 1 { // number must be positive integer
isPrime = false
}
else if i <= 3 {
isPrime = true
}
else {
for j in 2...i/2 // here i am using loop from 2 to i/2 because it will reduces the iteration.
{
if i%j == 0 { // number must have only 1 factor except 1. so use break: no need to check further
isPrime = false
break
}
}
}
if isPrime {
print(i)
}
}
}
func getPrimeNumbers(rangeOfNum: Int) -> [Int]{
var numArr = [Int]()
var primeNumArr = [Int]()
var currentNum = 0
for i in 0...rangeOfNum{
currentNum = i
var counter = 0
if currentNum > 1{
numArr.append(currentNum)
for j in numArr{
if currentNum % j == 0{
counter += 1
}
}
if counter == 1{
primeNumArr.append(currentNum)
}
}
}
print(primeNumArr)
print(primeNumArr.count)
return primeNumArr
}
Then just call the function with the max limit using this
getPrimeNumbers(rangeOfNum: 100)
What is happening in above code:
The numArr is created to keep track of what numbers have been used
Any number that is prime number is added/appended to primeNumArr
Current number shows the number that is being used at the moment
We start from 0 ... upto our range where we need prime numbers upto (with little modification it can be changed if the range starts from other number beside 0)
Remember, for a number to be Prime it should have 2 divisor means should be only completely divisible by 2 numbers. First is 1 and second is itself. (Completely divisible means having remainder 0)
The counter variable is used to keep count of how many numbers divide the current number being worked on.
Since 1 is only has 1 Divisor itself hence its not a Prime number so we start from number > 1.
First as soon as we get in, we add the current number being checked into the number array to keep track of numbers being used
We run for loop to on number array and check if the Current Number (which in our case will always be New and Greater then previous ones) when divided by numbers in numArr leaves a remainder of 0.
If Remainder is 0, we add 1 to the counter.
Since we are already ignoring 1, the max number of counter for a prime number should be 1 which means only divisible by itself (only because we are ignoring it being divisible by 1)
Hence if counter is equal to 1, it confirms that the number is prime and we add it to the primeNumArr
And that's it. This will give you all prime numbers within your range.
PS: This code is written on current version of swift
Optimised with less number of loops
Considered below conditions
Even Number can not be prime number expect 2 so started top loop form 3 adding 2
Any prime number can not multiplier of even number expect 2 so started inner loop form 3 adding 2
Maximum multiplier of any number if half that number
var primeNumbers:[Int] = [2]
for index in stride(from: 3, to: 100, by: 2) {
var count = 0
for indexJ in stride(from: 3, to: index/2, by: 2) {
if index % indexJ == 0 {
count += 1
}
if count == 1 {
break
}
}
if count == 0 {
primeNumbers.append(index)
}
}
print("primeNumbers ===", primeNumbers)
I finally figured it out lol, It might be not pretty but it works haha, Thanks for everyone's answer. I'll post what I came up with if maybe it will help anyone else.
for n in 2...100 {
if n % 2 == 0 && n < 3{
print(n)
} else if n % 3 == 0 && n > 6 {
} else if n % 5 == 0 && n > 5 {
} else if n % 7 == 0 && n > 7{
} else if n % 2 == 1 {
print(n)
}
}

What's wrong with this solution for neighbor cell counting of a matrix? (Swift)

I was given this problem to solve inside a Swift playground. I was told my answer is correct but not good enough (that's right, pretty vague).
/*
Write a Swift playground that takes an n x n grid of integers. Each integer can be either 1 or 0.
The playground then outputs an n x n grid where each block indicates the number of 1's around that block, (excluding the block itself) . For Block 0 on row 0, surrounding blocks are (0,1) (1,0) and (1,1). Similary for block (1,1) all the blocks around it are to be counted as surrounding blocks.
Requirements:
Make sure your solution works for any size grid.
Spend an hour and a half coding the logic and another hour cleaning your code (adding comments, cleaning variable and function names).
Optimize your functions to be O(n^2).
Your output lines should not have any trailing or leading whitespaces.
Please use hard coded example input constants below.
Examples:
Input Grid:
let sampleGrid = [[0,1,0], [0,0,0], [1,0,0]]
Console Output:
1 0 1
2 2 1
0 1 0
/////////////////
Input Grid:
let sampleGrid = [[0,1,0,0], [0,0,0,1], [1,0,0,1],[0,1,0,1]]
Console Output:
1 0 2 1
2 2 3 1
1 2 4 2
2 1 3 1
*/
/// An *Error* type
struct ComputationError : Error {
/// The message of the error
let message : String
}
/// This function computes a matrix result from the input *matrix*
/// where an integer value represents the number of adjacent cells
/// in the input *matrix* having a 1.
///
/// The algorithm is O(n^2), if n is the side length of the matrix:
///
/// for each row in rows of matrix
/// for each column in columns of matrix
/// for each matrix[row][column] cell if equal to 1
/// add a 1 to adjacent (valid) cell in result matrix
///
/// - Parameter matrix: input square matrix with values of 0 or 1 only
/// - Returns: a matrix of equal size to input matrix with computed adjacency values
/// - Throws: throws a ComputationError is the matrix is of invalid size or has invalid values (something other than 1 or 0)
func compute(matrix:[[Int]]) throws -> [[Int]] {
// The number of rows in matrix, which should equal the number of columns, ie side length, or n
let side = matrix.count
// The resulting matrix to return
var result:[[Int]] = []
// Initialize the result matrix
for _ in 0..<side {
result.append(Array<Int>(repeating: 0, count: side))
}
// A convenience constant to refer to the last element in a row or column
let last = side-1
// Iterate over rows in matrix
for row in 0..<side {
if matrix[row].count < side {
throw ComputationError(message:"Invalid number of columns (\(matrix[row].count)), should match number of rows (\(side))")
}
// Iterate over columns in matrix
for column in 0..<side {
// Consider this cell if it is 1, otherwise skip
// If it is 1, then add a 1 to all valid adjacent cells
// in result matrix.
if matrix[row][column] == 1 {
if 0 < row {
if 0 < column {
result[row-1][column-1] += 1
}
result[row-1][column] += 1
if column < last {
result[row-1][column+1] += 1
}
}
if 0 < column {
result[row][column-1] += 1
}
if column < last {
result[row][column+1] += 1
}
if row < last {
if 0 < column {
result[row+1][column-1] += 1
}
result[row+1][column] += 1
if column < last {
result[row+1][column+1] += 1
}
}
}
else if matrix[row][column] == 0 {
// ok
}
// If value is neither 0 or 1 throw an error
else {
throw ComputationError(message:"Invalid value (\(matrix[row][column])) encountered at row \(row) and column \(column)")
}
}
}
return result
}
/// Print *matrix* to console by iterating over each row in the
/// matrix and each column in the row, regardless of the count
/// of columns in the row. The output is row-wise and a single
/// space delimits columns, with no leading or trailing whitespace.
///
/// - Parameter matrix: an array of array of Int
func print(matrix:[[Int]]) {
let rows = matrix.count
for row in 0..<rows {
let columns = matrix[row].count
var line = ""
for column in 0..<columns {
if 0 < column {
line += " "
}
line += "\(matrix[row][column])"
}
print(line)
}
}
do {
print(matrix:try compute(matrix: [[0,1,0], [0,0,0], [1,0,0]]))
}
catch let error {
print(error)
}
do {
print()
print(matrix:try compute(matrix: [[0,1,0,0], [0,0,0,1], [1,0,0,1],[0,1,0,1]]))
}
catch let error {
print(error)
}
// test for exception
do {
print()
print(matrix:try compute(matrix: [[0,1], [0,0,0], [1,0,0]]))
}
catch let error {
print(error)
}
// test for exception
do {
print()
print(matrix:try compute(matrix: [[0,1,0], [3,0,0], [1,0,0]]))
}
catch let error {
print(error)
}
They were likely looking for something in a functional programming style and you probably needed to demonstrate that your solution is O(n^2).
for example:
// let sampleGrid = [[0,1,0], [0,0,0], [1,0,0]]
let sampleGrid = [[0,1,0,0], [0,0,0,1], [1,0,0,1],[0,1,0,1]]
func printMatrix(_ m:[[Any]])
{
print( m.map{ $0.map{"\($0)"}.joined(separator:" ")}.joined(separator:"\n") )
}
let emptyLine = [Array(repeating:0, count:sampleGrid.first!.count)]
let left = sampleGrid.map{ [0] + $0.dropLast() } // O(n)
let right = sampleGrid.map{ $0.dropFirst() + [0] } // O(n)
let up = emptyLine + sampleGrid.dropLast() // O(n)
let down = sampleGrid.dropFirst() + emptyLine // O(n)
let leftRight = zip(left,right).map{zip($0,$1).map{$0+$1}} // O(n^2)
let upDown = zip(up,down).map{zip($0,$1).map{$0+$1}} // O(n^2)
let cornersUp = emptyLine + leftRight.dropLast() // O(n)
let cornersDown = leftRight.dropFirst() + emptyLine // O(n)
let sides = zip(leftRight,upDown).map{zip($0,$1).map{$0+$1}} // O(n^2)
let corners = zip(cornersUp,cornersDown).map{zip($0,$1).map{$0+$1}} // O(n^2)
// 6 x O(n) + 5 x O(n^2) ==> O(n^2)
let neighbourCounts = zip(sides,corners).map{zip($0,$1).map{$0+$1}} // O(n^2)
print("SampleGrid:")
printMatrix(sampleGrid)
print("\nNeighbour counts:")
printMatrix(neighbourCounts)
...
SampleGrid:
0 1 0 0
0 0 0 1
1 0 0 1
0 1 0 1
Neighbour counts:
1 0 2 1
2 2 3 1
1 2 4 2
2 1 3 1

Sum of Printed For Loop in Swift

For a project, I'm trying to find the sum of the multiples of both 3 and 5 under 10,000 using Swift. Insert NoobJokes.
Printing the multiples of both 3 and 5 was fairly easy using a ForLoop, but I'm wondering how I can..."sum" all of the items that I printed.
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0 {
print(i)
}
}
(468 individual numbers printed; how can they be summed?)
Just a little walk through about the process. First you will need a variable which can hold the value of your sum, whenever loop will get execute. You can define an optional variable of type Int or initialize it with a default value same as I have done in the first line. Every time the loop will execute, i which is either multiple of 3 or 5 will be added to the totalSum and after last iteration you ll get your result.
var totalSum = 0
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0
{
print(i)
totalSum = totalSum + i
}
}
print (totalSum)
In Swift you can do it without a repeat loop:
let numberOfDivisiblesBy3And5 = (0...10000).filter{ $0 % 3 == 0 || $0 % 5 == 0 }.count
Or to get the sum of the items:
let sumOfDivisiblesBy3And5 = (0...10000).filter{ $0 % 3 == 0 || $0 % 5 == 0 }.reduce(0, {$0 + $1})
range : to specify the range of numbers for operation to act on.
here we are using filter method to filter out numbers that are multiple of 3 and 5 and then sum the filtered values.
(reduce(0,+) does the job)
let sum = (3...n).filter({($0 % 3) * ($0 % 5) == 0}).reduce(0,+)
You just need to sum the resulting i like below
var sum = 0
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0 {
sum = sum + i
print(i)
}
}
Now sum contains the Sum of the values
Try this:
var sum = 0
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0 {
sum = sum + i
print(i)
}
}
print(sum)
In the Bottom line, this should to be working.
var sum = 0
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0 {
sum += i
print(i)
}
}
print(sum)

How to find all numbers divisible by another number in swift?

How do I find all the numbers divisible by another number in swift that have a remainder of 0? This is a Fizzbuzz related question.
Lets say that...
let number = 150
And I want to do something like...
print("Fizz") // for all the numbers where the remainder of number % 3 == 0.
So if number was 15, it would print "Fizz" 5 times.
This will work
let number = 150
for num in 1...number {
if num % 3 == 0 {
print("Fizz :\(num)")
}
}
you can just loop through the number and check with your desired divisible number if the remainder is 0 then print fizz
let number = 15
for i in 0..<number {
if i % 3 == 0 {
print("\(i) Fizz")
}
}
It will print Fizz 5 times with the i value, that which number is Fizz.
Simply try this code: (You can simply replace num with any Int number and divider that is also an Int value which is used to divide all numbers till num. )
override func viewDidLoad() {
let num:Int = 15
let divider:Int = 3
var counter:Int = divider
while counter <= num {
print("Fizz")
counter += divider
}
}
func fizzbuzz(number: Int) -> String {
if number % 3 == 0 && number % 5 == 0 {
return "Fizz Buzz"
} else if number % 3 == 0 {
return "Fizz"
} else if number % 5 == 0 {
return "Buzz"
} else {
return String(number)
}
}
https://www.hackingwithswift.com/guide/ios-classic/1/3/challenge

Check a multiple in Swift?

I am trying to find the odd numbers and a multiple of 7 between a 1 to 100 and append them into an array. I have got this far:
var results: [Int] = []
for n in 1...100 {
if n / 2 != 0 && 7 / 100 == 0 {
results.append(n)
}
}
Your conditions are incorrect. You want to use "modular arithmetic"
Odd numbers are not divisible by 2. To check this use:
if n % 2 != 0
The % is the mod function and it returns the remainder of the division (e.g. 5 / 2 is 2.5 but integers don't have decimals, so the integer result is 2 with a remainder of 1 and 5 / 2 => 2 and 5 % 2 => 1)
To check if it's divisible by 7, use the same principle:
if n % 7 == 0
The remainder is 0 if the dividend is divisible by the divisor. The complete if condition is:
if n % 2 != 0 && n % 7 == 0
You can also use n % 2 == 1 because the remainder is always 1. The result of any mod function, a % b, is always between 0 and b - 1.
Or, using the new function isMultiple(of:, that final condition would be:
if !n.isMultiple(of: 2) && n.isMultiple(of: 7)
Swift 5:
Since Swift 5 has been released, you could use isMultiple(of:) method.
In your case, you should check if it is not multiple of ... :
if !n.isMultiple(of: 2)
Swift 5 is coming with isMultiple(of:) method for integers , so you can try
let res = Array(1...100).filter { !$0.isMultiple(of:2) && $0.isMultiple(of:7) }
Here is an efficient and concise way of getting the odd multiples of 7 less than or equal to 100 :
let results: [Int] = Array(stride(from: 7, through: 100, by: 14))
You can also use the built-in filter to do an operation on only qualified members of an array. Here is how that'd go in your case for example
var result = Array(1...100).filter { (number) -> Bool in
return (number % 2 != 0 && number % 7 == 0)
}
print(result) // will print [7, 21, 35, 49, 63, 77, 91]
You can read more about filter in the doc but here is the basics: it goes through each element and collects elements that return true on the condition. So it filters the array and returns what you want