Answers for "Find primes in numbers"

Go
0

Find primes in numbers

// Find primes in numbers

fn prime_factors(n: i64) -> String {
  let mut n = n as u64;
  let mut d = 2;
  let mut mem = std::collections::BTreeMap::new();
  while d <= n {
    if n % d == 0 {
      n /= d;
      let old = mem.entry(d).or_insert(0);
      *old += 1;
    } else {
      d += 1;
    }
  }
  mem.iter().map(|(key, val)| match *val {
    1 => format!("({})", key),
    _ => format!("({}**{})", key, val),
  }).collect::<String>()
}

fn main() {
    println!("Primes in numbers = {} ", prime_factors(7775460));
    println!("Primes in numbers = {} ", prime_factors(13*17*3*26));
    println!("Primes in numbers = {} ", prime_factors(14));
}
Posted by: Guest on October-08-2021
0

Find primes in numbers

// Find primes in numbers

package main

import "fmt"

func PrimeFactors(n int) (out string) {
  t, d := 0, 2
  for {
    if n % d != 0 {
      if t == 1 { out += fmt.Sprintf("(%d)", d) }
      if t >  1 { out += fmt.Sprintf("(%d**%d)", d, t) }
      if n == 1 { break }
      t = 0; d++; continue
    }
    n /= d
    t++
  }
  return
}

func main() {
    fmt.Printf("Sum of x + y = %s\n", PrimeFactors(7775460))   // (2**2)(3**3)(5)(7)(11**2)(17) 
    fmt.Printf("Sum of x + y = %s\n", PrimeFactors(13*17*3*26))
    fmt.Printf("Sum of x + y = %s\n", PrimeFactors(14))
}
Posted by: Guest on October-08-2021

Browse Popular Code Answers by Language