-1

i'm a novice with swift and wanted to create a method that will take an integer as its parameter and use a fencepost loop to print the factors of that number. This should be separated by the word "and".

For example, the call printFactors(24) should print the following output: 1 and 2 and 3 and 4 and 6 and 8 and 12 and 24

After thinking; i understand how to do it outside of the swift language; but need help with it in swift.

Here is what i had concluded before considering the swift language.

public void printFactors(int n) {
   for (int i=1; i <=n; i++) {
      if (n % i == 0) {
         if (i == 1) {
            System.out.print(i);
         } 
         else {
            System.out.print(" and " + i);
         }
      } 
   }
}

Help is greatly appreciated. Also how would i take the "solution" and output it as on a label? would i set the solution to a var?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 4
    Where's your Swift code? It's trivial to translate that Java code into Swift. This is not a free code translation service. Please make your own attempt first. Update your question with what you have tried and explain what issue you are having with the Swift code. – rmaddy Oct 19 '16 at 22:22
  • i just said i was a novice and aren't exactly familiar with it. No; stack is not a free code translation service; but it's a learning tool. Everyone learns differently and i wanted to see the solution; especially to something so innocuous. I don't the point of the feedback as it's purely subjective. – leahyjwilliam Oct 19 '16 at 22:40
  • 2
    You need to click on the help link above and read the section about asking questions. – rmaddy Oct 19 '16 at 22:46

2 Answers2

1

I agree with @rmaddy, in that Stack Overflow is not for free code translation. However, I already happened to have similar code handy that only required small changes:

func factor(number: Int) -> String {
    var string = ""
    for i in 1...number {
        if number % i == 0 {
            if i == 1 {
                string += "\(i)"
            } else {
                string += "and \(i)"
            }
        }
    }
    return string
}

To use:

let output = factor(number: 24)
print(output) // 1 and 2 and 3 and 4 and 6 and 8 and 12 and 24

Or with a label:

let outputText = factor(number: 24)
label.text = outputText

Hopefully this helps!

Nik
  • 1,664
  • 2
  • 14
  • 27
0
func printFactors(n: Int) {
  var result: String = ""
  for i in 1...n {
    guard n % i == 0  else {continue}
    result += i == 1 ? "1" : " and \(i)"
  }
  print(result)
}

printFactors(24)
Roman Siro
  • 226
  • 1
  • 11