Problem solution · Go

Codeforces 665F — Four Divisors

Codeforces 665F — Four Divisors: a Go solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Direct simulation
Source
EndlessCheng Codeforces Go
Length
50 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Codeforces 665F — Four Divisors, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 50 lines of Go from the credited upstream file 665F.go.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from EndlessCheng Codeforces Go by Σndless (EndlessCheng) and is used under the MIT licence.

Full codeCodeforces 665F — Four Divisors · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io"	"math") // https://github.com/EndlessChengfunc cf665F(in io.Reader, out io.Writer) {	var n int	Fscan(in, &n)	m := int(math.Sqrt(float64(n)))	pi := make([]int, m+1)	pi2 := make([]int, m+1)	for i := 1; i <= m; i++ {		pi[i] = i - 1		pi2[i] = n/i - 1	} 	for i := 2; i <= m; i++ {		prePi := pi[i-1]		if pi[i] > prePi {			for j := 1; j <= min(m, n/(i*i)); j++ {				if i*j <= m {					pi2[j] -= pi2[i*j] - prePi				} else {					pi2[j] -= pi[n/(i*j)] - prePi				}			}			for j := m; j >= i*i; j-- {				pi[j] -= pi[j/i] - prePi			}		}	} 	ans := pi[int(math.Cbrt(float64(n)))] // p^3 的个数	for i := 2; i <= m; i++ {		if pi[i] > pi[i-1] { // i 是质数(记作 p)			// p * q <= n			// 所以 p < q <= n/p			// 所以 q 的个数就是 pi(n/p) - pi(p)			ans += pi2[i] - pi[i]		}	}	Fprint(out, ans)} //func main() { cf665F(os.Stdin, os.Stdout) } 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗