Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

23
LINES

< > BotCompany Repo | #1030361 // collatzSequence - Collatz sequence for a number (as iterator). returns final 1 and initial number

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (2754L/17K).

1  
static ItIt<BigInt> collatzSequence(long n) {
2  
  ret collatzSequence(bigInt(n));
3  
}
4  
5  
static ItIt<BigInt> collatzSequence(BigInt _n) {
6  
  ret new ItIt<BigInt> {
7  
    BigInt three = bigInt(3);
8  
    BigInt n;
9  
    
10  
    public bool hasNext() {
11  
      ret neq(n, BigInt.ONE);
12  
    }
13  
    
14  
    public BigInt next() {
15  
      if (n == null) ret n = _n; // first number
16  
      if (even(n.intValue()))
17  
        n = div(n, BigInt.TWO);
18  
      else
19  
        n = plus(mul(n, three), BigInt.ONE);
20  
      ret n;
21  
    }
22  
  };
23  
}

Author comment

Began life as a copy of #1030359

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, vouqrxazstgt

No comments. add comment

Snippet ID: #1030361
Snippet name: collatzSequence - Collatz sequence for a number (as iterator). returns final 1 and initial number
Eternal ID of this version: #1030361/4
Text MD5: 1e7e86c1ee37560ee7ca9cca99940d32
Transpilation MD5: 1e3078bfd9392994c31d0155bdb21f96
Author: stefan
Category: javax / maths
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-12-09 15:12:00
Source code size: 516 bytes / 23 lines
Pitched / IR pitched: No / No
Views / Downloads: 121 / 178
Version history: 3 change(s)
Referenced in: [show references]