#include<bits/stdc++.h>
using namespace std;

#define int long long
#define endl "\n"
#define REP(i,a,n) for(int i=a;i<n;++i)
#define REPR(i,a,n) for(int i=a;i>n;--i)
#define RUP(a,b) ((a+b-1)/(b))
#define ALL(v) (v).begin(),(v).end()
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define MOD 1000000007
#define INF LLONG_MAX/2

typedef long long ll;
typedef pair<int,int> Pii;
typedef tuple<int,int,int> Tiii;
typedef vector<int> Vi;
typedef vector<Vi> VVi;
typedef vector<Pii> VPii;
typedef vector<string> Vs;

template<class T> inline bool chmax(T& a,T b){if(a<b){a=b;return 1;}return 0;}
template<class T> inline bool chmin(T& a,T b){if(a>b){a=b;return 1;}return 0;}
template<class T> void YesNo(T a) {cout<<(a?"Yes":"No")<<endl;}
template<class T> void YESNO(T a) {cout<<(a?"YES":"NO")<<endl;}
void vin(Vi &v){REP(i,0,(v).size()) cin>>v[i];}
void vin(Vi &v,Vi &v2){REP(i,0,(v).size()) cin>>v[i]>>v2[i];}
void vout(Vi &v){for(int i=0;i<(v).size();i++) cout<<v[i]<<" ";cout<<endl;}
int gcd(int a,int b){return b?gcd(b,a%b):a;}
int lcm(int a,int b){return a/gcd(a,b)*b;}
void uniq(Vi &v){sort(v.begin(),v.end()); v.erase(unique(v.begin(),v.end()),v.end());}
int ctoi(char c){if(c>='0'&&c<='9'){return c-'0';}return 0;}
void accum(Vi &v){REP(i,1,(v).size()) v[i]+=v[i-1];}
bool comp(Pii a,Pii b){
    if(a.second != b.second) return a.second<b.second;
    else return a.first<b.first;
}

void solve(std::string s, long long k){
    Vi a;
    int now=1,ans=0;
    if(s.size()==1){cout<<k/2<<endl;return;}
    REP(i,1,s.size()){
        if(s[i]==s[i-1]){
            now++;
        }else{
            a.pb(now);
            now=1;
        }
        if(i==s.size()-1) a.pb(now);
    }
    if(a.size()==1){
        cout<<(s.size()*k)/2<<endl;
        return;
    }
    if(s[0]!=s[s.size()-1]) REP(i,0,a.size()) ans += (a[i]/2)*k;
    else{
        REP(i,1,a.size()-1) ans += (a[i]/2)*k;
        ans += a[0]/2;
        ans += a[a.size()-1]/2;
        ans += (a[0]+a[a.size()-1])/2*(k-1);
    }
    cout<<ans<<endl;
}

// Generated by 1.1.5 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
signed main(){
    std::string S;
    std::cin >> S;
    long long K;
    scanf("%lld",&K);
    solve(S, K);
    return 0;
}


#include <bits/stdc++.h>
#define all(x) (x).begin(),(x).end()
#define print(x) cout << (x) << endl
typedef long long ll;
const ll MOD = 1000000007;
const ll MOD2 = 998244353;

using namespace std;

int main(){
    string s;   cin >> s;
    ll k;  cin >> k;
    int l = s.length();
    if(l == 1){print(k / 2); return 0;}
    ll i = 1, cnt = 0;
    vector<int> c(l,0);
    while(i < l){
        if(s[i] == s[i-1]){
            c[i] = 1;
            i += 2;
        }else   i++;
    }
    for(int i=0; i<l; i++) cnt += c[i];
    ll ans = cnt * k;
    if(s[0] == s[l-1]){
        if(c[l-1] == 0) ans += (k - 1);
    }
    print(ans);
}


#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i< (n); i++)
using ll = long long;
using namespace std;

int main(){
	string S;
	ll K;
	cin >> S >> K;
	ll ans = 0;
	string A = "", B="";
	int i = 1;
	A += S[0];
	while (i<S.size() ) {
		if (S[i] != S[0]) break;
		A += S[i];
		i++;
	}
	while (i<S.size() ) {
		B += S[i];
		i++;
	}
	B += A;
	char now = B[0];
	ll cnt = 1;
	for (int i = 1; i < B.size(); i++) {
		if (B[i] == now)	cnt++;
		else {
			ans += (cnt/2)*K;
			cnt = 1;
			now = B[i];
		}
	}
	ans += (cnt/2)*(K-1);
	ll p = cnt - A.size();
	ans += (p/2) + A.size()/2;

	if (B.size() == 1) ans = K/2;

	cout << ans << endl;
	return 0;
}


#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i< (n); i++)
using ll = long long;
using namespace std;

int main(){
	string S;
	ll K;
	cin >> S >> K;
	ll ans = 0;
	string A = "", B="";
	int i = 1;
	A += S[0];
	while (i<S.size() ) {
		if (S[i] != S[0]) break;
		A += S[i];
		i++;
	}
	while (i<S.size() ) {
		B += S[i];
		i++;
	}
	B += A;
	char now = B[0];
	ll cnt = 1;
	for (int i = 1; i < B.size(); i++) {
		if (B[i] == now)	cnt++;
		else {
			ans += (cnt/2)*K;
			cnt = 1;
			now = B[i];
		}
	}
	ans += (cnt/2)*(K-1);
	ll p = cnt - A.size();
	ans += (p/2) + A.size()/2;

	if (B.size() == 1) ans = K/2;

	cout << ans << endl;
	return 0;


#include <stdio.h>
#include <stdlib.h>

int main()
{
	long long K;
	char S[101];
	scanf("%s", S);
	scanf("%lld", &K);

	int l, flag = 1;
	for (l = 0; S[l+1] != 0; l++) if (S[l] != S[l+1]) flag = 0;
	if (flag == 1) {
		printf("%lld\n", K * (l + 1) / 2);
		fflush(stdout);
		return 0;
	}

	int i, count = 0, tmp = 1;
	if (S[0] == S[l++]) flag = 1;
	for (i = 1; i < l; i++) {
		if (S[i] == S[i-1]) tmp++;
		else {
			count += tmp / 2;
			tmp = 1;
		}
	}
	count += tmp / 2;
	for (i = 1; S[i] == S[i-1]; i++);
	if (i % 2 == 0) flag = 0;
	for (i = l - 2; S[i] == S[i+1]; i--);
	if ((l - i - 1) % 2 == 0) flag = 0;

	if (flag == 1) printf("%lld\n", K * count + (K - 1));
	else printf("%lld\n", K * count);
	fflush(stdout);
	return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MOD1 1000000007
#define MOD2 998244353
#define LIMIT1 200002
#define LIMIT2 500002
typedef long long ll;
typedef long double ld;
typedef const void cv;
#define rep(i,n) for((i)=0;(i)<(n);(i)++)
#define per(i,n) for((i)=(n)-1;(i)>=0;(i)--)
#define max(a,b) ((a)>(b) ? (a) : (b))
#define min(a,b) ((a)<(b) ? (a) : (b))
#define zt(a,b) (max((a),(b))-min((a),(b)))
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll nPr(int n,int r){ll i,result=1;rep(i,r){result*=(ll)(n-i);}return result;}
ll nCr(int n,int r){ll i,result=1;if(n<r) return 0;rep(i,min(r,n-r)){result*=(ll)(n-i);result/=(ll)(i+1);}return result;}
#define nHr(n,r) nCr((int)((n)+(r)+1),(int)(r))
#define sankaku(x) (((x)*((x)+1))/2)
int dx[8]={1,0,-1,0,1,-1,-1,1};
int dy[8]={0,1,0,-1,1,1,-1,-1};
int upint(const void *a, const void *b) { return *(int *)a < *(int *)b ? -1 : *(int *)a > *(int *)b ? 1 : 0; }
int downint(const void *a, const void *b) { return *(int *)a < *(int *)b ? 1 : *(int *)a > *(int *)b ? -1 : 0; }
int upchar(const void* left, const void* right) {return strcmp((char *)left,(char *)right);}
int downchar(const void* left, const void* right) {return strcmp((char *)right,(char *)left);}
ll modpow(ll a, ll n, ll mod) {
  ll res = 1;
  while (n > 0) {
    if (n & 1) res = res * a % mod;
    a = a * a % mod;
    n >>= 1;
  }
  return res;
}
void initialize(){

}
int main(void){
  initialize();
  ll n,m,i,j,k,result=0;
  ll a=0,b=0;
  char s[LIMIT1];

  scanf("%s",s);
  scanf("%lld",&k);
  j=1;
  n = strlen(s);
  rep(i,n){
	if(i!=n-1&&s[i]==s[i+1]) j++;
    else{
      result += (ll)floorl(j/2.0);
      j=1;
    }
  }
  a=1;
  b=1;
  rep(i,n-1){
    if(s[i]!=s[i+1]) break;
    a++;
  }
  per(i,n-1){
    if(s[i]!=s[i+1]) break;
    b++;
  }
  result *= k;
  if(s[0]==s[n-1]){
    if(a==b && a==n) result = (ll)floorl(n*k/2);
    else result -= (k-1)*(ll)(floorl(a/2.0)+floorl(b/2.0)-floorl((a+b)/2.0));
  }
  printf("%lld",result);
  return 0;
}


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdint.h>
#include<stdbool.h>
#include<tgmath.h>
#include<sys/queue.h>
#include<time.h>
#define ll long long
#define min(a, b) ((a) > (b) ? (b) : (a))
#define max(a, b) ((a) > (b) ? (a) : (b))
#define miin(a, b, c) min((a), min((b), (c)))
#define maax(a, b, c) max((a), max((b), (c)))
#define mod 1000000007

char s[111];
ll k;

main(){
    scanf("%s%lld", s, &k);
    int l = strlen(s);
    if(s[0] != s[l-1]){
        ll a = 0, b = 1;
        for(int i=1; i<l; i++){
            if(s[i] == s[i-1]){
                b++;
            }else {
                a += b / 2;
                b = 1;
            }
        }
        a += b/2;
        printf("%lld\n", k * a);
        return 0;
    }
    ll a = 0, b = 1, c = 1, i = 1;
    for(;i<l && s[i]==s[i-1]; i++){
        c++;
    }
    if(i == l){
        printf("%lld\n", l * k / 2);
        return 0;
    }
    for(; i<l; i++){
        if(s[i]==s[i-1]){
            b++;
        }else {
            a += b / 2;
            b = 1;
        }
    }
    printf("%lld\n", a * k + ((b + c)/2)*(k-1)+ b/2 + c/2);
    return 0;
}


#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef long long ll;

int main(void){
  char s[101];
  ll k;

  scanf("%s %lld",s ,&k);

  ll count = 0;
  int len = strlen(s);

  if(s[0] == s[len-1] && s[0] == s[1]){
    s[0] = '&';
    count ++;
  }

  for(int i = 0;s[i+1] != '\0';i ++){
    if(s[i] == s[i+1]){
      s[i+1] = '&';
      count ++;
    }
  }

  if(s[0] == s[len-1]){
    printf("%lld",k*count + k-1);
  }

  else{
    printf("%lld",k*count);
  }

  return 0;

}


#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef long long ll;

int main(void){
  char s[101];
  ll k;

  scanf("%s %lld",s ,&k);

  ll count = 0;
  for(int i = 0;s[i+1] != '\0';i ++){
    if(s[i] == s[i+1]){
      s[i] = '&';
      count ++;
    }
  }

  int len = strlen(s);

  if(s[0] == s[len-1]){
    printf("%lld",k*count + k-1);
  }

  else{
    printf("%lld",k*count);
  }

  return 0;

}


#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef long long ll;

int main(void){
  char s[101];
  ll k;

  scanf("%s %lld",s ,&k);

  ll count = 0;
  for(int i = 0;s[i+1] != '\0';i ++){
    if(s[i] == s[i+1]){
      s[i+1] = '&';
      count ++;
    }
  }

  int len = strlen(s);

  if(s[0] == s[len-1]){
    printf("%lld",k*count + k-1);
  }

  else{
    printf("%lld",k*count);
  }

  return 0;

}


// inputに入力データ全体が入る
// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	S = input[0];
	//K = input[1];
	var k = parseInt(input[1], 10);
	n = S.length;
	//console.log(S,k,n);

	 S1=[];
	var cnt =0;var f = 0;
	for(i=0;i<n;i++){if( S.substr(i,1)==S.substr(i+1,1)){f++;
	                                                   //  S1[i] =f;
	                                                     }
	                              else if(f > 0){S1[i-f] =f+1;
	                                             f = f/2;
	                                            f = Math.ceil(f);
	                                            cnt = cnt + f;
                                                var f = 0;
	                                         //   S1[i]=f;
	                                            }
                                                         else{S1[i]=f+1;}
                                              }
//	console.log(i,cnt,k);
//	console.log(S1);
	//console.log(S1.shift(),S1.pop());
 //   console.log(S1.length)
if (n==1){cnt = Math.floor(k/2);}
                  else if (S1.length == 1){//console.log('***');
                                           t=S1[0]*k;
                                           cnt = Math.floor(t/2);
                                    //     console.log(t);
                                             }
                             else if

	                         (S.substr(0,1)==S.substr(n-1,1)){
	                                      //  console.log(S1);
                                            x = S1[0]%2;
	                                        y = S1.pop()%2;
	                                      //  console.log(x,y);
	                                           if (x ==1 && y==1)
	                                              { cnt=cnt*k+k-1;}
                                                 else {// console.log('*');
                                                      cnt = cnt*k;}}
                               else{cnt = cnt*k;}
                                                    //     }}

	console.log(cnt);
	//console.log(cnt*k);
	//if (n==1){cnt = Math.ceil(cnt*k/2);}else{cnt = cnt*k;}
//	console.log(cnt);
	}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const lineList = require('fs').readFileSync('/dev/stdin','utf8').trim().split('\n')

const s = lineList[0]
const k = parseInt(lineList[1])

var blockList = s.match(/(.)\1*/g)

var total = 0
var head = blockList[0]
var tail = blockList[blockList.length-1]

if(blockList.length === 1) {
  total = Math.floor(blockList[0].length * k  / 2)
} else if(head[0] === tail[0]) {
  blockList.pop()
  blockList.shift()
  total = blockList.reduce((acc, e, i) => Math.floor(acc + e.length / 2), 0) * k
  total += Math.floor(head.length / 2)
  total += Math.floor(tail.length / 2)
  total += Math.floor((head.length + tail.length) / 2) * (k - 1)
} else {
  total = blockList.reduce((acc, e, i) => Math.floor(acc + e.length / 2), 0) * k
}

console.log(total)


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	var Input = input.split("\n");

  	var str = Input[0];
  	var n = Number(Input[1])

    var arr = str.split("")
    var cnt = 1
    var cntArr = []

    for(var i in arr){

      if(arr[i] == arr[parseInt(i,10) + 1]){
        cnt = cnt + 1
      }else{
        cntArr.push(cnt)
        cnt = 1
      }
    }

  	var ans = 0

  	var len = arr.length
    var cntlen = cntArr.length

    var a =0
    var b = 0
    var c =0

    if(cntlen == 1){

       ans = Math.floor( cntArr[0] * n / 2 )

    }else if(arr[0] == arr[len -1]){

      for(var j in cntArr){

        if(j == 0){
        	var a = Math.floor( cntArr[j] / 2 )
        }else if(j == cntlen - 1){
        	var b = Math.floor( ( cntArr[0] + cntArr[j] ) /2 )
            var c = Math.floor( cntArr[j] / 2 )
        }else{
	        ans = ans + Math.floor( cntArr[j] / 2 )
        }
      }

      ans = ans * n + b * (n -1) + a + c

    }else{
      for(var j in cntArr){
        ans = ans + Math.floor( cntArr[j] / 2 )
      }
      ans = ans * n
    }

	//出力
	console.log(ans);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


var obj = init();
Main();
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
function next(){return obj.next();}
function hasNext(){return obj.hasNext();}
function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");}
function init(){
  var inputFile = myin();
  var returnObj = {
    "list" : inputFile, "index" : 0, "max" : inputFile.length,
    "hasNext" : function(){return (this.index < this.max);},
    "next" : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(t){console.log(t);}//標準出力
function myerr(t){console.error(t);}//標準エラー出力
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す　1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main(){
  var s = next();
  var N = nextInt();
  var len = s.length;
  if(len == 1){
    myout(Math.floor((len * N) / 2));
    return;
  }
  var s1 = myconv(s, 6);
  var s2 = myconv(s + s, 6);

  var output = 0;
  var s1count = 0;
  var s2count = 0;

  for(var i = 1; i < s1.length; i++){
    var mae = s1[i - 1];
    var ato = s1[i];
    if(mae == ato){
       s1count++;
       s1[i] = "X";
    }
  }
  for(var i = 1; i < s2.length; i++){
    var mae = s2[i - 1];
    var ato = s2[i];
    if(mae == ato){
       s2count++;
       s2[i] = "X";
    }
  }
  if(N == 1){
    myout(s1count);
  }else{
    myout((s2count - s1count) * (N - 1) + s1count);
  }

}


var input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
var obj = {
  "list" : input,
  "index" : 0,
  "max" : input.length,
  "next" : function(){
    if(!this.hasNext()){throw "NoSuchElementException:次に要素は無いよ";}
    var returnObj = this.list[this.index];
    this.index++;
    return returnObj;
  },
  "hasNext" : function(){return (this.index < this.max);}
}
Main();
function next(){return obj.next();}
function hasNext(){return obj.hasNext();}
function myout(t){console.log(t);}//standard output
function myerr(t){console.error(t);}//standard error
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す　1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main(){
  var s = next();
  var N = myconv(next(),1);
  var len = s.length;
  s = s + s;
  s = myconv(s,6);
  var output = 0;
  for(var i = 1; i < len; i++){
    var mae = s[i - 1];
    var ato = s[i];
    if(mae == ato){
       output++;
       s[i] = "X";
    }
  }
  if(s[len - 1] == s[len]){
     myout(output * N + (N - 1));
  }else{
     myout(output * N);
  }
}


function Main(input) {
  input.trim();
  input = input.split("\n");
var S = input[0].split("");
var K = input[1];
  var Count = 1;
  var Change = 0;
for(var i=0;i<S.length;i++){
  if(S[i] == S[i+1]){
    Count ++;
  }else{
    Change += Math.floor(Count/2);
    Count = 1;
  }
}
Change *= K;
if(S[0] == S[S.length-1]){
  Change += Number(K);
}
  console.log(Change);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func init() {
	const maxWord = (1 << 30)
	buf := []byte{}
	sc.Buffer(buf, maxWord)
	sc.Split(bufio.ScanWords)
}

func input() string {
	sc.Scan()
	return sc.Text()
}

func solve(s string, k int) int {
	n := len(s)
	if n == 1 {
		return n * k / 2
	}

	numPer1 := 0
	seqNum := 1
	for i := 1; i < n; i++ {
		if s[i] == s[i-1] {
			seqNum++
		} else {
			numPer1 += seqNum / 2
			seqNum = 1
		}
	}
	lastSeqNum := seqNum

	if s[0] != s[n-1] {
		numPer1 += lastSeqNum / 2
		return numPer1 * k
	}
	if lastSeqNum == n {
		return n * k / 2
	}

	firstSeqNum := 1
	for i := 1; i < n; i++ {
		if s[i] != s[i-1] {
			break
		}
		firstSeqNum++
	}

	ans := numPer1
	numPer1 -= firstSeqNum / 2
	numPer1 += (firstSeqNum + lastSeqNum) / 2
	ans += numPer1 * (k - 1)
	ans += lastSeqNum / 2

	return ans
}

func main() {
	s := input()
	k, _ := strconv.Atoi(input())
	fmt.Println(solve(s, k))
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

// min, max, asub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func asub(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

func main() {
	sc.Split(bufio.ScanWords)

	S := []byte(getString())
	k := getInt()

	cnt := 1
	ans := 0
	for i := 1; i < len(S); i++ {
		if S[i] == S[i-1] {
			cnt++
		} else {
			ans += cnt / 2
			cnt = 1
		}
	}
	ans += cnt / 2

	if cnt == len(S) {
		out(len(S) * k / 2)
		return
	}

	c := S[0]
	left := 0
	for i := 0; i < len(S); i++ {
		if S[i] == c {
			left++
		} else {
			break
		}
	}
	right := 0
	for i := len(S) - 1; i >= 0; i-- {
		if S[i] == c {
			right++
		} else {
			break
		}
	}

	x := left/2 + right/2 - (left+right)/2

	// out(ans, x, left, right)
	out(ans*k - x*(k-1))
}


package main

import "fmt"

func countPair(S string) (pair int) {
	for i := 0; i+1 < len(S); i++ {
		if S[i] == S[i+1] {
			pair++
			i++
		}
	}
	return pair
}

func main() {
	var s1, s2 string
	var k, ans int
	fmt.Scan(&s1, &k)
	m := make(map[byte]int, 0)
	for i := 0; i < len(s1); i++ {
		m[s1[i]]++
	}
	p1 := countPair(s1)
	s2 = s1 + s1
	p2 := countPair(s2)
	if len(m) == 1 {
		ans = len(s1) * k / 2
	} else if p1*2 == p2 {
		ans = p1 * k
	} else {
		d := p2 - p1*2
		ans = p1*k + (k-1)*d
	}
	fmt.Println(ans)
}


package main

import "fmt"

func main() {
	// Code for A - Connection and Disconnection
	var S string
	var K int
	fmt.Scan(&S, &K)

	var count1, count2 int
	for i := 0; i < len(S)-1; i++ {
		if S[i] == S[i+1] {
			count1++
			i++
		}
	}

	if count1 == 0 {
		fmt.Println(len(S) * K / 2)
	} else if S[0] != S[len(S)-1] {
		fmt.Println(count1 * K)
	} else {
		count2 = 0
		T := S + S
		for i := 0; i < len(T)-1; i++ {
			if T[i] == T[i+1] {
				count2++
				i++
			}
		}

		fmt.Println((K-1)*(count2-count1) + count1)
	}

}


package main

import "fmt"

func main() {
	// Code for A - Connection and Disconnection
	var S string
	var K int
	fmt.Scan(&S, &K)

	var count1, count2 int
	for i := 0; i < len(S)-1; i++ {
		if S[i] == S[i+1] {
			count1++
			i++
		}
	}

	if S[0] != S[len(S)-1] {
		fmt.Println(count1 * K)
	} else {
		count2 = 0
		T := S + S
		for i := 0; i < len(T)-1; i++ {
			if T[i] == T[i+1] {
				count2++
				i++
			}
		}

		fmt.Println((K-1)*(count2-count1) + count1)
	}

}


package main

import "fmt"

func main() {
	// Code for A - Connection and Disconnection
	var S string
	var K int
	fmt.Scan(&S, &K)

	var count1, count2 int
	for i := 0; i < len(S)-1; i++ {
		if S[i] == S[i+1] {
			count1++
			S = S[0:i+1] + "_" + S[i+2:len(S)]
		}
	}

	if S[0] != S[len(S)-1] {
		fmt.Println(count1 * K)
	} else {
		count2 = 0
		T := S + S
		for i := 0; i < len(T)-1; i++ {
			if T[i] == T[i+1] {
				count2++
				T = T[0:i+1] + "_" + T[i+2:len(T)]
			}
		}

		fmt.Println(T)
		fmt.Println((K-1)*(count2-count1) + count1)
	}

}


S=gets.chomp
K=gets.to_i

if S.chars.uniq.length == 1
    puts S.length*K/2
    exit 0
end

a = S.chars.chunk_while {|c1,c2| c1 == c2 }.map(&:count)
ret = a.inject(0) {|sum,cnt| sum += cnt/2 * K }
ret += K-1 if S[0] == S[-1] && a[0].odd? && a[-1].odd?
puts ret


S=gets.chomp
K=gets.to_i

if S.chars.uniq.length == 1
    puts S.length*K/2
    exit 0
end

pc = nil
cnt = 0
a = []
S.each_char do |c|
    if pc == c
        cnt += 1
    else
        a << [pc,cnt]
        pc = c
        cnt = 1
    end
end
a << [pc,cnt]
a.shift

if a[0][0] == a[-1][0]
    ret = 0
    a[1..-2].each do |c,cnt|
        ret += cnt/2 * K
    end
    ret += (a[0][1]+a[-1][1])/2*(K-1)
    ret += a[0][1]/2
    ret += a[-1][1]/2
    puts ret
else
    ret = 0
    a.each do |c,cnt|
        ret += cnt/2 * K
    end
    puts ret
end


s = gets.chomp
k = gets.to_i

rl = s.chars.slice_when { |i, j| i != j }.map { |e| e.size }
count = k * rl.map { |e| e / 2 }.inject(:+)

if rl.size == 1
  puts s.size * k / 2
elsif s[0] == s[-1]
  puts count - (k - 1) * (rl[0] / 2 + rl[-1] / 2 - (rl[0] + rl[-1]) / 2)
else
  puts count
end


s = gets.chomp.split("")
k = gets.to_i
s_double = s * 2

increment_when_odd = 0
(1...s.size).each do |i|
  if s[i - 1] == s[i]
    s[i] = 'A'
    increment_when_odd += 1
  end
end

increment_when_even = 0
(1...s_double.size).each do |i|
  if s_double[i - 1] == s_double[i]
    s_double[i] = 'A'
    increment_when_even += 1
  end
end
increment_when_even -= increment_when_odd

even = k / 2
odd = k.odd? ? even + 1 : even

puts increment_when_odd * odd + increment_when_even * even


s = gets.chomp.split("")
k = gets.to_i
if s.size == 1
  puts k / 2
else
  change_count = 0
  (1...s.size).each do |i|
    if s[i - 1] == s[i]
      s[i] = 'A'
      change_count += 1
    end
  end
  puts change_count * k
end


n=gets.chomp.split("").map(&:to_s)
v=n[0]
n.push(v)
#p n
t=gets.to_i
i=1
count=0
count
count_zero=0
if n.length-1==1
    p 0
    exit
end
while i<=n.length-1
    #p i
    if i==n.length-1 && n[i-1]==n[i]
        n[i]="#"
             count_zero=1
             i+=1
             next
    elsif n[i-1]==n[i]
        n[i]="#"
        count+=1
        i+=1
        next

    end
    i+=1
end

p count*t+count_zero*(t-1)


use std::io::Read;

fn run_length_encoding<T: Clone + Eq>(a: &[T]) -> Vec<(T, usize)> {
    if a.len() == 0 {
        return vec![];
    }
    let mut x = a[0].clone();
    let mut cnt = 1;
    let mut ans = vec![];
    for y in &a[1..] {
        if x == *y {
            cnt += 1;
        } else {
            ans.push((x, cnt));
            x = y.clone();
            cnt = 1;
        }
    }
    ans.push((x, cnt));
    ans
}

fn run() {
    let mut s = String::new();
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut it = s.trim().split_whitespace();
    let s: Vec<char> = it.next().unwrap().chars().collect();
    let k: usize = it.next().unwrap().parse().unwrap();
    let mut s = run_length_encoding(&s);
    let ans = if s.len() == 1 {
        s[0].1 * k / 2
    } else if s[0].0 == s.last().unwrap().0 {
        let mut ans = 0usize;
        let b = s.pop().unwrap();
        let f = s.remove(0);
        ans += b.1 / 2 + f.1 / 2 + (b.1 + f.1) / 2 * (k - 1);
        for (_, c) in s {
            ans += c / 2 * k;
        }
        ans
    } else {
        let mut ans = 0;
        for (_, c) in s {
            ans += c / 2 * k;
        }
        ans
    };
    println!("{}", ans);
}

fn main() {
    run();
}


#[macro_use]
mod input_mcr {
    // ref: tanakh <https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8>
    // diff: using Parser
    #[macro_export(local_inner_macros)]
    macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut parser = Parser::from_str($s);
        input_inner!{parser, $($r)*}
    };
    (parser = $parser:ident, $($r:tt)*) => {
        input_inner!{$parser, $($r)*}
    };
    (new_stdin_parser = $parser:ident, $($r:tt)*) => {
        let stdin = std::io::stdin();
        let reader = std::io::BufReader::new(stdin.lock());
        let mut $parser = Parser::new(reader);
        input_inner!{$parser, $($r)*}
    };
    ($($r:tt)*) => {
        input!{new_stdin_parser = parser, $($r)*}
    };
}

    #[macro_export(local_inner_macros)]
    macro_rules! input_inner {
    ($parser:ident) => {};
    ($parser:ident, ) => {};
    ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($parser, $t);
        input_inner!{$parser $($r)*}
    };
}

    #[macro_export(local_inner_macros)]
    macro_rules! read_value {
    ($parser:ident, ( $($t:tt),* )) => {
        ( $(read_value!($parser, $t)),* )
    };
    ($parser:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($parser, $t)).collect::<Vec<_>>()
    };
    ($parser:ident, chars) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()
    };
    ($parser:ident, char_) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()[0]
    };
    ($parser:ident, usize1) => {
        read_value!($parser, usize) - 1
    };
    ($parser:ident, line) => {
        $parser.next_line()
    };
    ($parser:ident, line_) => {
        $parser.next_line().chars().collect::<Vec<char>>()
    };
    ($parser:ident, i64_) => {
        $parser.fast_i64()
    };
    ($parser:ident, usize_) => {
        $parser.fast_i64() as usize
    };
    ($parser:ident, usize1_) => {
        ($parser.fast_i64() - 1) as usize
    };
    ($parser:ident, $t:ty) => {
        $parser.next::<$t>().expect("Parse error")
    };
}

    use std::io;
    use std::io::BufRead;
    use std::str;

    // ref: tatsuya6502 <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e>
    // ref: wariuni <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e#comment-7040a5ae96305e884eb9>
    // diff: using std::io::BufRead::fill_buf()
    pub struct Parser<R> {
        pub reader: R,
        buf: Vec<u8>,
        pos: usize,
    }

    impl Parser<io::Empty> {
        pub fn from_str(s: &str) -> Parser<io::Empty> {
            Parser {
                reader: io::empty(),
                buf: s.as_bytes().to_vec(),
                pos: 0,
            }
        }
    }

    impl<R: BufRead> Parser<R> {
        pub fn new(reader: R) -> Parser<R> {
            Parser {
                reader: reader,
                buf: vec![],
                pos: 0,
            }
        }
        pub fn update_buf(&mut self) {
            self.buf.clear();
            self.pos = 0;
            loop {
                let (len, complete) = {
                    let buf2 = self.reader.fill_buf().unwrap();
                    self.buf.extend_from_slice(buf2);
                    let len = buf2.len();
                    (len, buf2[len - 1] <= 0x20)
                };
                self.reader.consume(len);
                if complete {
                    break;
                }
            }
        }
        pub fn next<T: str::FromStr>(&mut self) -> Result<T, T::Err> {
            loop {
                let mut begin = self.pos;
                while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                    begin += 1;
                }
                let mut end = begin;
                while end < self.buf.len() && (self.buf[end] > 0x20) {
                    end += 1;
                }
                if begin != self.buf.len() {
                    self.pos = end;
                    return unsafe { str::from_utf8_unchecked(&self.buf[begin..end]) }.parse::<T>();
                } else {
                    self.update_buf();
                }
            }
        }
        pub fn next_line(&mut self) -> String {
            loop {
                let mut begin = self.pos;
                if begin < self.buf.len() && (self.buf[begin] < 0x20) {
                    begin += 1;
                }
                let mut end = begin;
                while end < self.buf.len() && (self.buf[end] >= 0x20) {
                    end += 1;
                }
                if begin != self.buf.len() {
                    self.pos = end;
                    return unsafe { str::from_utf8_unchecked(&self.buf[begin..end]) }.to_string();
                } else {
                    self.update_buf();
                }
            }
        }
        pub fn fast_i64(&mut self) -> i64 {
            loop {
                let mut begin = self.pos;
                while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                    begin += 1;
                }
                if begin == self.buf.len() {
                    self.update_buf();
                    continue;
                }
                let mut res = 0;
                let (is_positive, mut end) = match self.buf[begin] {
                    b'+' => (true, begin + 1),
                    b'-' => (false, begin + 1),
                    _ => (true, begin),
                };
                while end < self.buf.len() && (self.buf[end] > 0x20) {
                    res = res * 10 + (self.buf[end] as i64 - '0' as i64);
                    end += 1;
                }
                if begin != self.buf.len() {
                    self.pos = end;
                    return if is_positive { res } else { -res };
                } else {
                    self.update_buf();
                }
            }
        }
    }
}

mod group {
    pub fn group<T: PartialEq + Eq + Clone + Copy>(xs: &[T]) -> Vec<(T, usize)> {
        let mut res = vec![];
        let n = xs.len();
        for i in 0..n {
            if i == 0 || xs[i - 1] != xs[i] {
                res.push((xs[i], 1));
            } else {
                let m = res.len();
                res[m - 1].1 += 1;
            }
        }
        res
    }

    #[test]
    fn test_group_1() {
        let xs = [1, 2, 2, 3, 3];
        let res = group(&xs);
        assert_eq!(res, [(1, 1), (2, 2), (3, 2)]);
    }

    #[test]
    fn test_split_continuity_2() {
        let xs = [1, 1, 2, 2, 3];
        let res = group(&xs);
        assert_eq!(res, [(1, 2), (2, 2), (3, 1)]);
    }
}

use input_mcr::*;
use std::cmp::*;

use group::*;

fn main() {
    input! {
        s: chars,
        m: usize,
    }
    let xs = group(&s);
    if xs.len() == 1 {
        let res = s.len() * m / 2;
        println!("{}", res);
    } else if xs[0].0 == xs[xs.len() - 1].0 {
        let mut res = 0;
        res += xs[0].1 / 2;
        for i in 1..xs.len() - 1 {
            res += xs[i].1 / 2 * m;
        }
        res += (xs[0].1 + xs[xs.len() - 1].1) / 2 * (m - 1);
        res += xs[xs.len() - 1].1 / 2;
        println!("{}", res);
    } else {
        let mut res = 0;
        for &x in &xs {
            res += x.1 / 2 * m;
        }
        println!("{}", res);
    }
}


use std::str::FromStr;
use std::fmt::Debug;
use std::cmp;
#[allow(dead_code)]
fn read_as_vec<T>() -> Vec<T>
where T: FromStr, <T as FromStr>::Err : Debug{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().split_whitespace().map(|c| T::from_str(c).unwrap()).collect()

}

#[allow(dead_code)]
fn read_as_string() -> String{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

fn main(){
    let s = read_as_string().chars().collect::<Vec<char>>();
    let n = s.len();
    let t = read_as_vec::<usize>()[0];

    if s.iter().all(|x| s[0] == *x){
    //if (s.len() == 1) || (s.len() == 2 && s[0] == s[1]){
        println!("{}", s.len()*t/2);
        return;
    }else if s.len() == 2{
        println!("0");
        return;
    }

    let mut i = 0;
    let mut x = 0;
    let (mut first_len, mut last_len) = (0, 0);
    while i < n{
        let mut j = 0;
        while i+j < n && s[i] == s[i+j]{
            j += 1;
        }
        if i == 0{
            first_len = j;
        }

        if i + j == n{
            last_len = j;
        }
        i += j;
        x += j/2;
    }
    let mut y = 0;
    if first_len%2 == 1 && last_len%2 == 1 && s[0] == s[n-1]{
        y = 1;
    }
    println!("{}", x*t + y*(t-1));
}


use proconio::marker::{Bytes, Chars};
use proconio::{fastout, input};
use std::collections::*;

#[fastout]
fn main() {
    input! {
        mut s: Chars,
        k: i64,
    }

    if s.iter().collect::<HashSet<_>>().len() == 1 {
        println!("{}", s.len() as i64 * k / 2);
        return;
    }

    let mut v = Vec::new();
    let mut now = s[0];
    let mut count = 1;
    for i in 1..s.len() {
        if now == s[i] {
            count += 1;
        } else {
            v.push(count);
            count = 1;
            now = s[i];
        }
    }
    v.push(count);

    let mut ans = v.iter().map(|x| x / 2).sum::<i64>() * k;
    if s[0] == s[s.len() - 1] {
        ans -= v[0] / 2 + v[v.len() - 1] / 2 - (v[0] + v[v.len() - 1]) / 2;
    }
    println!("{}", ans);
}


#![allow(unused_macros)]
#![allow(dead_code)]
#![allow(unused_imports)]

use itertools::Itertools;
use proconio::*;
use std::collections::VecDeque;
use std::io::stdin;
use std::str::FromStr;
use text_io::*;

const U_INF: usize = 1 << 60;
const I_INF: isize = 1 << 60;

fn main() {
    let mut sc = Scanner::new();
    let mut s = sc.next_chars();
    let k = sc.next_usize();

    let c = s[0];
    let mut all_same = true;
    for &ci in &s {
        if c != ci {
            all_same = false;
        }
    }

    if all_same {
        println!("{}", s.len() * k / 2);
    } else {
        let mut ans = 0;
        for i in 1..s.len() {
            if s[i - 1] == s[i] {
                ans += k as isize;
                s[i] = '!';
            }
        }

        if s[0] == s[s.len() - 1] {
            let mut a = 0;
            let c = s[0];
            for i in 1..s.len() {
                if s[i] != c {
                    a = i;
                    break;
                }
            }

            let mut b = 0;
            for i in (1..s.len() - 1).rev() {
                if s[i] != c {
                    b = s.len() - i - 1;
                    break;
                }
            }

            ans -= (k as isize - 1) * (a as isize / 2 + b as isize / 2 - (a + b) as isize / 2);
        }

        println!("{}", ans);
    };
}

pub struct Scanner {
    buf: VecDeque<String>,
}

impl Scanner {
    pub fn new() -> Self {
        Self {
            buf: VecDeque::new(),
        }
    }

    fn scan_line(&mut self) {
        let mut flag = 0;
        while self.buf.is_empty() {
            let mut s = String::new();
            stdin().read_line(&mut s).unwrap();
            let mut iter = s.split_whitespace().peekable();
            if iter.peek().is_none() {
                if flag >= 5 {
                    panic!("There is no input!");
                }
                flag += 1;
                continue;
            }

            for si in iter {
                self.buf.push_back(si.to_string());
            }
        }
    }

    pub fn next<T: FromStr>(&mut self) -> T {
        self.scan_line();
        self.buf
            .pop_front()
            .unwrap()
            .parse()
            .unwrap_or_else(|_| panic!("Couldn't parse!"))
    }

    pub fn next_usize(&mut self) -> usize {
        self.next()
    }

    pub fn next_isize(&mut self) -> isize {
        self.next()
    }

    pub fn next_chars(&mut self) -> Vec<char> {
        self.next::<String>().chars().collect_vec()
    }

    pub fn next_string(&mut self) -> String {
        self.next()
    }

    pub fn fill_vec_line<T: FromStr>(&mut self, v: &mut Vec<T>) {
        for vi in v {
            *vi = self.next();
        }
    }

    pub fn fill_vec<T: FromStr>(&mut self, v: &mut Vec<Vec<T>>) {
        for vi in v {
            for vii in vi {
                *vii = self.next();
            }
        }
    }

    pub fn make_vec_line<T: FromStr + Default + Clone>(&mut self, i: usize) -> Vec<T> {
        let mut v = vec![Default::default(); i];
        self.fill_vec_line(&mut v);
        v
    }

    pub fn make_vec<T: FromStr + Default + Clone>(&mut self, i: usize, j: usize) -> Vec<Vec<T>> {
        let mut v = vec![vec![Default::default(); j]; i];
        self.fill_vec(&mut v);
        v
    }
}


#![allow(unused_macros)]
#![allow(dead_code)]
#![allow(unused_imports)]

use itertools::Itertools;
use proconio::*;
use std::collections::VecDeque;
use std::io::stdin;
use std::str::FromStr;
use text_io::*;

const U_INF: usize = 1 << 60;
const I_INF: isize = 1 << 60;

fn main() {
    let mut sc = Scanner::new();
    let mut s = sc.next_chars();
    let k = sc.next_usize();

    let c = s[0];
    let mut all_same = true;
    for &ci in &s {
        if c != ci {
            all_same = false;
        }
    }

    if all_same {
        println!("{}", s.len() * k / 2);
    } else {
        let mut ans = 0;
        for i in 1..s.len() {
            if s[i - 1] == s[i] {
                ans += k;
                s[i] = '!';
            }
        }

        if s[0] == s[s.len() - 1] {
            let mut a = 0;
            let c = s[0];
            for i in 1..s.len() {
                if s[i] != c {
                    a = i;
                    break;
                }
            }

            let mut b = 0;
            for i in (1..s.len() - 1).rev() {
                if s[i] != c {
                    b = s.len() - i - 1;
                    break;
                }
            }

            ans -= (k - 1) * (a / 2 + b / 2 - (a + b) / 2);
        }

        println!("{}", ans);
    };
}

pub struct Scanner {
    buf: VecDeque<String>,
}

impl Scanner {
    pub fn new() -> Self {
        Self {
            buf: VecDeque::new(),
        }
    }

    fn scan_line(&mut self) {
        let mut flag = 0;
        while self.buf.is_empty() {
            let mut s = String::new();
            stdin().read_line(&mut s).unwrap();
            let mut iter = s.split_whitespace().peekable();
            if iter.peek().is_none() {
                if flag >= 5 {
                    panic!("There is no input!");
                }
                flag += 1;
                continue;
            }

            for si in iter {
                self.buf.push_back(si.to_string());
            }
        }
    }

    pub fn next<T: FromStr>(&mut self) -> T {
        self.scan_line();
        self.buf
            .pop_front()
            .unwrap()
            .parse()
            .unwrap_or_else(|_| panic!("Couldn't parse!"))
    }

    pub fn next_usize(&mut self) -> usize {
        self.next()
    }

    pub fn next_isize(&mut self) -> isize {
        self.next()
    }

    pub fn next_chars(&mut self) -> Vec<char> {
        self.next::<String>().chars().collect_vec()
    }

    pub fn next_string(&mut self) -> String {
        self.next()
    }

    pub fn fill_vec_line<T: FromStr>(&mut self, v: &mut Vec<T>) {
        for vi in v {
            *vi = self.next();
        }
    }

    pub fn fill_vec<T: FromStr>(&mut self, v: &mut Vec<Vec<T>>) {
        for vi in v {
            for vii in vi {
                *vii = self.next();
            }
        }
    }

    pub fn make_vec_line<T: FromStr + Default + Clone>(&mut self, i: usize) -> Vec<T> {
        let mut v = vec![Default::default(); i];
        self.fill_vec_line(&mut v);
        v
    }

    pub fn make_vec<T: FromStr + Default + Clone>(&mut self, i: usize, j: usize) -> Vec<Vec<T>> {
        let mut v = vec![vec![Default::default(); j]; i];
        self.fill_vec(&mut v);
        v
    }
}


let S = readLine()!.characters.map { String($0) }
let K = Int(readLine()!)!

func minReplacement(s: [String]) -> Int {
  var count = 0

  var left = 0

  while left < s.count {
    var right = left
    while right < s.count && s[left] == s[right] {
      right += 1
    }
    count += (right - left) / 2
    left = right
  }
  return count
}

if Set(S).count <= 1 {
  print(Int(Double(S.count) / 2.0 * Double(K)))
} else {
	let first = minReplacement(S)
	let second = minReplacement(S + S)
  	let diff = second - first
  	print(first + diff * (K - 1))
}


let S = readLine()!.characters.map { String($0) }
let K = Int(readLine()!)!

func minReplacement(s: [String]) -> Int {
  var count = 0

  var left = 0

  while left < s.count {
    var right = left
    while right < s.count && s[left] == s[right] {
      right += 1
    }
    count += (right - left) / 2
    left = right
  }
  return count
}

if Set(S).count <= 1 {
  print(S.count * K / 2)
} else {
	let first = minReplacement(S)
	let second = minReplacement(S + S)
  	let diff = second - first
  	print(first + diff * (K - 1))
}


let S = readLine()!.characters.map { String($0) }
let K = Int(readLine()!)!

func minReplacement(s: [String]) -> Int {
  var count = 0

  var left = 0

  while left < s.count {
    var right = left
    while right < s.count && s[left] == s[right] {
      right += 1
    }
    count += (right - left) / 2
    left = right
  }
  return count
}

if Set(S).count <= 1 {
  print(Int(Double(S.count) / 2.0 * K))
} else {
	let first = minReplacement(S)
	let second = minReplacement(S + S)
  	let diff = second - first
  	print(first + diff * (K - 1))
}


let S = readLine()!.characters.map { String($0) }
let K = Int(readLine()!)!

func minReplacement(s: [String]) -> Int {
  var count = 0

  var left = 0

  while left < s.count {
    var right = left
    while right < s.count && s[left] == s[right] {
      right += 1
    }
    count += (right - left) / 2
    left = right
  }
  return count
}

if Set(S).count <= 1 {
  print(S.count / 2 * K)
} else {
	let first = minReplacement(S)
	let second = minReplacement(S + S)
  	let diff = second - first
  	print(first + diff * (K - 1))
}


let S = readLine()!.characters.map { String($0) }
let K = Int(readLine()!)!

func minReplacement(s: [String]) -> Int {
  var count = 0

  var left = 0

  while left < s.count {
    var right = left
    while right < s.count && s[left] == s[right] {
      right += 1
    }
    count += (right - left) / 2
    left = right
  }
  return count
}

if Set(S).count <= 1 {
  print(S.count / 2)
} else {
	let first = minReplacement(S)
	let second = minReplacement(S + S)
  	let diff = second - first
  	print(first + diff * (K - 1))
}


const fs = require('fs');
let [s, k] = fs.readFileSync('/dev/stdin', 'utf-8').split('\n');
k = parseInt(k);

function exec(s: string): [number, string] {
  let count = 0;
  let before = s[0];
  for (let i = 1; i < s.length; ++i) {
    if (before !== s[i]) {
      before = s[i];
    } else {
      before = null;
      count++;
    }
  }
  return [count, before];
}

let [count, last] = exec(s);
if (s[0] !== last) {
  console.log(count * k);
} else {
  let [even, last] = exec(s[0] + s);
  if (s[0] !== last) {
    console.log((k >> 1) * (count + even) + (k & 1) * count);
  } else {
    console.log(count + (k - 1) * even);
  }
}


import { readFileSync } from 'fs'
function main() {
  const input = readFileSync('/dev/stdin', 'utf8')
  const [string, stringK] = input.split('\n').map(v => v.trim())
  const k = Number(stringK)
  const s = string.split('')
  // 1pattern
  if (s.length === 1) {
    console.log(Math.floor(k / 2))
    return
  }
  let allSameFlg = true
  let count = 0
  let changeFlg = false
  let combo = 1
  let initialCombo = 1
  let initialComboFlg = true
  const s2 = s.reduce((a, b)=> {
    if (a === b){
      combo++
      if (changeFlg === false) {
        count++
        changeFlg = true
      } else {
        changeFlg = false
      }
    } else {
      if (initialComboFlg) {
        initialCombo = combo
        initialComboFlg = false
      }
      combo = 1
      changeFlg = false
      allSameFlg = false
    }
    return b
  })
  if (allSameFlg) {
    initialCombo = combo
  }
  const lastCombo = combo
  // そのほかのパターン
  count *= k
  if (s.length !== 2 && s[0] === s[s.length - 1]) {
    if (initialCombo % 2 !== 0 && combo % 2 !== 0) {
      count += (k - 1)
    }
  }

  // 奇数で全部同じパターン
  if (allSameFlg && s.length % 2 !== 0) {
    console.log(Math.floor((s.length * k) / 2))
  } else {
    console.log(count)
  }
}
main()


const fs = require('fs');
let [s, k] = fs.readFileSync('/dev/stdin', 'utf-8').split('\n');
k = parseInt(k);

function exec(s: string): [number, string] {
  let count = 0;
  let before = s[0];
  for (let i = 1; i < s.length; ++i) {
    if (before !== s[i]) {
      before = s[i];
    } else {
      before = null;
      count++;
    }
  }
  return [count, before];
}

let [count, last] = exec(s);
if (s[0] !== last) {
  console.log(count * k);
} else {
  let [even, last] = exec(s[0] + s);
  console.log((k >> 1) * (odd + even) + (k & 1) * odd);
}


const fs = require('fs');
let [s, k] = fs.readFileSync('/dev/stdin', 'utf-8').split('\n');
k = parseInt(k);

function exec(s: string): [number, boolean] {
  let count = 0;
  let before = s[0];
  for (let i = 1; i < s.length; ++i) {
    if (before !== s[i]) {
      before = s[i];
    } else {
      before = null;
      count++;
    }
  }
  return [count, before === null];
}

let [count, lastChanged] = exec(s);
if (lastChanged || s[0] !== s.slice(-1)) {
  console.log(count * k);
} else {
  let [even, c] = exec(s[0] + s);
  console.log((k >> 1) * (odd + even) + (k & 1) * odd);
}


// var st = Date.now()

import { readFileSync } from 'fs'
function main() {
  const input = readFileSync('/dev/stdin', 'utf8')
  const [string, stringK] = input.split('\n').map(v => v.trim())
  const k = Number(stringK)
  const s = string.split('')
  // 1pattern
  if (s.length === 1) {
    console.log(Math.floor(k / 2))
    return
  }
  let oddSameFlg = true
  let count = 0
  let changeFlg = false
  const s2 = s.reduce((a, b)=> {
    if (a === b){
      if (changeFlg === false) {
        count++
        changeFlg = true
      } else {
        changeFlg = false
      }
    } else {
      changeFlg = false
      oddSameFlg = false
    }
    return b
  })

  // そのほかのパターン
  count *= k
  if (s.length !== 2 && s[0] === s[s.length - 1] && s[0] === s[1] && s[s.length - 1] === s[s.length - 2]) {
    count += (k - 1)
  }

  // 奇数で全部同じパターン
  if (oddSameFlg && s.length % 2 !== 0) {
    console.log(Math.floor((s.length * k) / 2))
  } else {
    console.log(count)
  }
}
main()
// const et = Date.now() - st
// console.log(et)


import sys
X = int(input())

def is_prime(n):
    for i in range(2, n + 1):
        if i * i > n:
            break
        if n % i == 0:
            return False
    return n != 1

number = X
while True:
    if is_prime(number) == True:
        print(number)
        sys.exit()
    else:
        number = number  + 1


import math
X = int(input())

def isprime(n):
    if n < 2:
        return False
    elif n == 2:
        return True
    elif n % 2 == 0:
        return False
    for i in range(3, math.floor(math.sqrt(n))+1, 2):
        if n % i == 0:
            return False
    return True

while isprime(X) is not True:
    X += 1

print(X)


import math
X = int(input())

def prime(a):
    for i in range(2, math.floor(math.sqrt(a)) + 1):
        if a % i == 0:
            return True
    return False

while prime(X):
    X += 1
print(X)


X=int(input())

def is_prime(x):
    if x<=1:
        return False

    for i in range(2,int(-(-x**0.5//1))+1):
        if x%i==0:
            return False

    return True

p=X
while not is_prime(p):
    p+=1

print(p)


import math

def is_prime(x):
    for j in range(x,10**5+3):
        count=0
        for k in range(2, int(math.sqrt(x))+1):
            if j % k == 0:
                count=1
                break
        if count==0:
            return j

x=int(input())
print(is_prime(x))


import math

def is_prime(x):
    for j in range(x+1,10**5):
        count=0
        for k in range(2, int(math.sqrt(x))):
            if j % k == 0:
                count=1
                break
        if count==0:
            return j

x=int(input())
print(is_prime(x))


import java.io.*;
import java.util.*;

public class Main {
  public static void main(String[] args) {
    FastScanner fs = new FastScanner();
    int X = fs.nextInt();
    while (!isPrime(X)) X++;
    System.out.println(X);
  }

  public static boolean isPrime(int n) {
    if(n < 2) return false;
    if(n == 2) return true;
    if(n % 2 == 0) return false;
    for(int i = 3; i * i <= n; i += 2) {
      if(n % i == 0) return false;
    }
    return true;
  }
}

class FastScanner {
  private final InputStream in = System.in;
  private final byte[] buffer = new byte[1024];
  private int ptr = 0;
  private int buflen = 0;

  private boolean hasNextByte() {
    if (ptr < buflen) {
      return true;
    } else {
      ptr = 0;
      try {
        buflen = in.read(buffer);
      } catch (IOException e) {
        e.printStackTrace();
      }
      if (buflen <= 0) {
        return false;
      }
    }
    return true;
  }

  private int readByte() {
    if (hasNextByte())
    return buffer[ptr++];
    else
    return -1;
  }

  private static boolean isPrintableChar(int c) {
    return 33 <= c && c <= 126;
  }

  public boolean hasNext() {
    while (hasNextByte() && !isPrintableChar(buffer[ptr]))
    ptr++;
    return hasNextByte();
  }

  public String next() {
    if (!hasNext())
    throw new NoSuchElementException();
    StringBuilder sb = new StringBuilder();
    int b = readByte();
    while (isPrintableChar(b)) {
      sb.appendCodePoint(b);
      b = readByte();
    }
    return sb.toString();
  }

  public long nextLong() {
    if (!hasNext())
    throw new NoSuchElementException();
    long n = 0;
    boolean minus = false;
    int b = readByte();
    if (b == '-') {
      minus = true;
      b = readByte();
    }
    if (b < '0' || '9' < b) {
      throw new NumberFormatException();
    }
    while (true) {
      if ('0' <= b && b <= '9') {
        n *= 10;
        n += b - '0';
      } else if (b == -1 || !isPrintableChar(b)) {
        return minus ? -n : n;
      } else {
      throw new NumberFormatException();
      }
      b = readByte();
    }
  }

  public int nextInt() {
    long nl = nextLong();
    if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
    throw new NumberFormatException();
    return (int) nl;
  }

  public double nextDouble() {
    return Double.parseDouble(next());
  }
}


import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        FastScanner fs = new FastScanner();
        int n = fs.nextInt();
        while (isPrime2(n) == false) {
            n++;
        }
        System.out.println(n);
    }

    public static boolean isPrime2(int n) {
        if (n == 1)
            return false;
        int prime_array[] = { 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, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193,
                197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
                317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
                449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587,
                593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719,
                727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859,
                863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 };
        for (int i : prime_array) {
            if (n > i && n % i == 0)
                return false;
            else if (n == i)
                return true;
        }
        return true;
    }

    public static int[] intArray(int n, FastScanner fs) {
        int array[] = new int[n];
        for (int i = 0; i < n; i++) {
            array[i] = fs.nextInt();
        }
        return array;
    }

    public static long[] longArray(int n, FastScanner fs) {
        long array[] = new long[n];
        for (int i = 0; i < n; i++) {
            array[i] = fs.nextLong();
        }
        return array;
    }

    public static String[] stringArray(int n, FastScanner fs) {
        String array[] = new String[n];
        for (int i = 0; i < n; i++) {
            array[i] = fs.next();
        }
        return array;
    }

    public static void checkArray(int[] array) {
        System.out.println(Arrays.toString(array));
    }

    public static void checkArray(long[] array) {
        System.out.println(Arrays.toString(array));
    }

    public static void checkArray(String[] array) {
        System.out.println(Arrays.toString(array));
    }

    public static void printArray(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            System.out.print(array[i]);
            System.out.print(' ');
        }
        System.out.println(array[array.length - 1]);
    }

    public static void printArray(long[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            System.out.print(array[i]);
            System.out.print(' ');
        }
        System.out.println(array[array.length - 1]);
    }

    public static void printArray(String[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            System.out.print(array[i]);
            System.out.print(' ');
        }
        System.out.println(array[array.length - 1]);
    }
}

class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() {
        if (hasNextByte())
            return buffer[ptr++];
        else
            return -1;
    }

    private static boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }

    public boolean hasNext() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr]))
            ptr++;
        return hasNextByte();
    }

    public String next() {
        if (!hasNext())
            throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext())
            throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            } else if (b == -1 || !isPrintableChar(b)) {
                return minus ? -n : n;
            } else {
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
            throw new NumberFormatException();
        return (int) nl;
    }

    public double nextDouble() {
        return Double.parseDouble(next());
    }
}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.List;
import java.util.NoSuchElementException;

public class Main {

	public static void main(String[] args) throws IOException {
		new Main().solve();
	}

	private void solve() throws IOException {
		try {
			//			solveA();
			//			solveB();
			solveC();
			//			 solveD();
			//			 solveE();
			//			 solveF();
		} finally {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.flush();
				out.close();
			}
		}

	}

	private void solveA() {
		String s = next();
		String t = next();
		out.println(t + s);
	}

	private void solveB() {
		long a = nextLong();
		long b = nextLong();
		long k = nextLong();

		if (k <= a) {
			out.println(a - k + " " + b);
		} else if (k <= a + b) {
			out.println(0 + " " + (b - (k - a)));
		} else {
			out.println(0 + " " + 0);
		}

	}

	private void solveC() {
		int x = nextInt();
		//2は素数
		if (x == 2) {
			out.println(2);
			return;
		}
		//２ではない偶数は素数になれないので奇数へ
		if (x % 2 == 0) {
			x++;
		}
		while (true) {
			boolean sosu = true;
			//奇数しか見ていないので偶数で割れるかの判定は不要
			for (int i = 3; i < x; i += 2) {
				if (x % i == 0) {
					sosu = false;
					break;
				}
			}
			if (sosu) {
				break;
			}
			//この時点では、素数の可能性は奇数のみ（２はすでに除外）
			x += 2;
		}
		out.println(x);
	}

	private void solveD() {
		int n = nextInt();

		out.println("");
	}

	private void solveE() {
		int n = nextInt();

		out.println("");
	}

	private void solveF() {
		int n = nextInt();

		out.println("");
	}

	/*
	 * 階乗計算の最大値
	 * もっと大きいのが必要ならここを修正
	 */
	private final int FACTORIAL_NUM = 111111;
	/*
	 * 階乗の事前計算（mod 済）
	 */
	private long[] factorial = new long[FACTORIAL_NUM];
	/*
	 * 逆数の事前計算（mod 済）
	 */
	private long[] reverseFactorial = new long[FACTORIAL_NUM];
	private boolean isInitFactorial = false;

	/**
	 * 階乗計算の事前累積和
	 * [1, 1, 2, 3, 4, 5, … FACTORIAL_NUM]
	 * mod済
	 */
	private void initFactorial(long mod) {
		factorial[0] = 1;
		for (int i = 1; i < FACTORIAL_NUM; i++) {
			factorial[i] = (factorial[i - 1] * i) % mod;
		}
	}

	/**
	 * 逆数の事前計算
	 * もっと速い方法があったので修正
	 */
	private void initReverseFactorial(long mod) {

		reverseFactorial[FACTORIAL_NUM - 1] = modInverse(factorial[FACTORIAL_NUM - 1], mod);
		for (int i = FACTORIAL_NUM - 2; i >= 0; i++) {
			/*
			 * 以下を利用する。
			 * これにより毎回modInverseしなくてよくなる
			 * (N!)^(-1) * N -> ((N - 1)!)^(-1)
			 * (N-1!)^(-1) * N -> ((N - 2)!)^(-1)
			 */
			reverseFactorial[i] = (reverseFactorial[i + 1] * (i + 1)) % mod;
		}
		//		reverseFactorial[0] = 1;
		//		for (int i = 0; i < FACTORIAL_NUM; i++) {
		//			reverseFactorial[i] = modInverse(factorial[i], mod);
		//		}
	}

	/**
	 * フェルマーの小定理を用いて逆元を求める。
	 * ある数xのmod p（pは素数）の逆数x'はx' = x^(p-2)
	 * 繰り返し二乗法を用いて計算する。
	 * http://satanic0258.hatenablog.com/entry/2016/04/29/004730
	 * {@link BigInteger#modInverse(BigInteger)}とどちらが速いか？
	 * @param x
	 * @return
	 */
	private long modInverse(long x, long mod) {
		long res = 1L;
		long k = mod - 2L;
		long y = x;
		while (k != 0) {
			if (k % 2 != 0) {
				res = (res * y) % mod;
			}
			y = (y * y) % mod;
			k /= 2;
		}
		return res;
	}

	private void initFactorialCalc(long mod) {
		if (isInitFactorial) {
			//初期化済みならreturn
			return;
		}
		//階乗の事前計算
		initFactorial(mod);
		//逆数の計算もしておく
		initReverseFactorial(mod);
		isInitFactorial = true;
	}

	/**
	 * 組み合わせ
	 * nCk -> n! / k!・(n-k)!
	 * @param n
	 * @param k
	 * @param mod
	 * @return
	 */
	private long combination(int n, int k, long mod) {
		initFactorialCalc(mod);
		if (k < 0 || n < k) {
			return 0;
		}

		//分子の計算
		long calResN = factorial[n];

		//分母の計算
		long calResNK = reverseFactorial[n - k];
		long calcResK = reverseFactorial[k];
		long denominator = (calResNK * calcResK) % mod;

		return (calResN * denominator) % mod;

	}

	/**
	 * 順列
	 * nPk -> n! / (n-k)!
	 * @param n
	 * @param k
	 * @return
	 */
	private long permutation(int n, int k, long mod) {
		initFactorialCalc(mod);
		if (k < 0 || n < k) {
			return 0;
		}
		long calResN = factorial[n];
		long calResNK = reverseFactorial[n - k];
		return (calResN * calResNK) % mod;
	}

	/**
	 * 多項係数
	 * 文字aをp個,bをq個,cをr個, dをs個 あわせてn個を1列に並べるときの並べ方
	 * n! / p!・q!・r!・s!
	 * @param n
	 * @param strNum
	 * @param mod
	 * @return
	 */
	private long multinominalCoefficient(int n, List<Integer> strNum, int mod) {
		initFactorialCalc(mod);

		long calResN = factorial[n];
		long calResDenomi = 1;
		for (Integer num : strNum) {
			calResDenomi *= reverseFactorial[num];
		}
		return (calResN * calResDenomi) % mod;
	}

	/**
	 * 重複組合せ nHr （同次積）
	 * nHr = (n+r-1)Cr
	 * 異なるn個のものから重複を許してr個取る組合せの総数
	 * 例：
	 * リンゴ，ミカン，牛肉の3種類の果物があります．これらの中から6個の食材を買って帰ります．
	 * このとき，何通りの買い方がありますか？ただし，含まれない食材があってもよいものとします
	 * @param n
	 * @param r
	 * @param mod
	 * @return
	 */
	private long homogeneousProduct(int n, int r, long mod) {
		if (n == 0 && r == 0) {
			return 1;
		}
		return combination(n + r - 1, r, mod);
	}

	private final PrintWriter out = new PrintWriter(System.out);
	private final InputStream in = System.in;
	private final byte[] buffer = new byte[1024];
	private int ptr = 0;
	private int buflen = 0;

	private boolean hasNextByte() {
		if (ptr < buflen) {
			return true;
		} else {
			ptr = 0;
			try {
				buflen = in.read(buffer);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (buflen <= 0) {
				return false;
			}
		}
		return true;
	}

	private int readByte() {
		if (hasNextByte())
			return buffer[ptr++];
		else
			return -1;
	}

	private static boolean isPrintableChar(int c) {
		return 33 <= c && c <= 126;
	}

	private void skipUnprintable() {
		while (hasNextByte() && !isPrintableChar(buffer[ptr]))
			ptr++;
	}

	public boolean hasNext() {
		skipUnprintable();
		return hasNextByte();
	}

	public int nextInt() {
		return Integer.parseInt(next());
	}

	public String next() {
		if (!hasNext())
			throw new NoSuchElementException();
		StringBuilder sb = new StringBuilder();
		int b = readByte();
		while (isPrintableChar(b)) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	public long nextLong() {
		if (!hasNext())
			throw new NoSuchElementException();
		long n = 0;
		boolean minus = false;
		int b = readByte();
		if (b == '-') {
			minus = true;
			b = readByte();
		}
		if (b < '0' || '9' < b) {
			throw new NumberFormatException();
		}
		while (true) {
			if ('0' <= b && b <= '9') {
				n *= 10;
				n += b - '0';
			} else if (b == -1 || !isPrintableChar(b)) {
				return minus ? -n : n;
			} else {
				throw new NumberFormatException();
			}
			b = readByte();
		}
	}
}


import java.util.ArrayList;
import java.util.Scanner;

// 20
public class Main {
    static int getMorePrime(int n) {
        ArrayList<Integer> primes = new ArrayList<Integer>();
        primes.add(2);
        int i = 2;
        while(true) {
            for(int j = 0 ; j < primes.size(); j++)
                if(i % primes.get(j) == 0) {
                    ++i;
                    j = 0;
                }
            if(i >= n) return i;
            primes.add(i);
            ++i;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        System.out.println(getMorePrime(n));
    }

}


import java.util.*;
import java.math.*;

public class Main {
    void solve(){
        Scanner scan = new Scanner(System.in);
        String x = scan.next();
        BigInteger a = new BigInteger(x);
        System.out.println(a.nextProbablePrime());
    }

    public static void main(String[] args){
        new Main().solve();
    }
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long N = sc.nextLong();

        for(long i = N; i*i <= 1000100; i++) {
            if(isPrime(i)) {
                System.out.println(i);
                break;
            }
        }

    }
    public static boolean isPrime(long N) {
        if(N == 1) return false;
        for(long i = 2; i * i <= N; i++) {
            if(N % i == 0) return false;
        }
        return true;
    }
}


/*author: hyperion_1724
  date:
*/

//Optional FAST

//#pragma GCC optimize("Ofast")
//#pragma GCC optimize("unroll-loops")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,fma,abm,mmx,avx,avx2,tune=native")

//Required Libraries

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>

//Required namespaces

using namespace std;
using namespace __gnu_pbds;

//Required defines

#define endl '\n'

#define READ(X) cin>>X;
#define READV(X) long long X; cin>>X;
#define READAR(A,N) long long A[N]; for(long long i=0;i<N;i++) {cin>>A[i];}
#define rz(A,N) A.resize(N);
#define sz(X) (long long)(X.size())
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define trav(x,A) for(auto &x:A)
#define FORI(a,b,c) for(long long a=b;a<c;a++)
#define FORD(a,b,c) for(long long a=b;a>c;a--)

//Required typedefs

typedef tree<long long,null_type,less<long long>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;
typedef tree<long long,null_type,greater<long long>,rb_tree_tag,tree_order_statistics_node_update> ordered_set1;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<long long,long long> pll;
typedef vector<int> veci;
typedef vector<long long> vecl;

//Required Constants

const long long inf=(long long)1e18;
const long long MOD=(long long)(1e9+7);
const long long INIT=(long long)(1e6+1);

//Required Functions

ll power(ll x,ll y)
{
    if (y == 0)
        return 1;
    ll p = power(x, y/2) % MOD;
    p = (p * p) % MOD;

    return (y%2 == 0)? p : (x * p) % MOD;
}
ll modInverse(ll a)
{
   return power(a,MOD-2);

}

//Work
bool isprime(ll z)
{
    for (ll i = 2; i*i <= z; i++)
    {
        if (z%i==0)
        {
            return false;
        }

    }
    return true;
}

int main()
{

    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

//-----------------------------------------------------------------------------------------------------------//

    READV(X);
    while (!isprime(X))
    {
        X++;
    }
    cout<<X<<endl;

//-----------------------------------------------------------------------------------------------------------//

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0; i<(n) ;i++)
#define pb push_back
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
#define sz(x) ((int)(x).size())
using ll=long long;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
#define MOD  1000000007
const ll INF=1e18;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b){ a = b; return 1; } return 0; }

bool isprime(long long int val) {
 if (val <= 1)return false;
 for (long long int i = 2; i*i <= val; i++) {
   if (val%i == 0LL)return false;
 }
 return true;//ç´ æ•°
}

int main(int argc, char const *argv[]) {
  int x;
  cin >> x;
  while(!isprime(x)) x++;
  cout << x << endl;
  return 0;
}


#include <iostream>
using namespace std;

int isPrime(int n){
    for(int i=2;i*i<=n;i++){
        if(n%i==0)
        return 0;
    }
    return 1;
}

int main() {
	// your code goes here

    int x,i;
	cin>>x;

	for(i=x;;i++)
	    if(isPrime(i))
	    break;
	 cout<<i<<endl;

	return 0;
}


#include<bits/stdc++.h>

using namespace std;

bool prime(int x)
{
	if(x<2 || x%2==0)
	return false;
	int root=sqrt(x);
	for(int i=3;i<=root;i+=2)
	{
		if(x%i==0)
		return false;
	}
	return true;
}
int main()
{
     int x;
     cin>>x;
     while(1)
     {
        bool res = prime(x);
     	if(res)
     	{
     		cout<<x;
     		return 0;
		}
		x++;
	 }
}


                                 /*Bismillahir Rahmanir Rahim*/

#include<bits/stdc++.h>
#include<cstring>
#include<vector>
#include<map>
#include<set>
#define ll long long int
#define dd double
using namespace std;
#define M 1000001
ll ara[M];
ll size=1000001;
void sieve()
   {
      int i, j, root;
      for(i = 2; i < size; i++) {
            ara[i] = 1;
         }
   root = sqrt(size);

      for(i = 2; i <= root; i++) {
   if(ara[i] == 1) {
for(j = 2; i * j <= size; j++) {
ara[i * j] = 0;
}

}
      }
   }

int main()
{
   ll t,n,i,j,x,a,b,y;

 sieve();
      cin>>n;

      if(ara[n]==1)
      cout<<n<<endl;
      else{
         for(i=n+1;;i++)
         {
            if (ara[i]==1)
            {
            cout<<i<<endl;
               break;
            }

      }

   }

}

//Apna Time Aayega :)


#include <stdio.h>
#include <math.h>

int main(void)
{
        int x,i,j,a;
        double rt;

        scanf("%d",&x);

        a=0;
        for(i=x;i>0;i++){
                rt=sqrt((double)x);
                j=2;
                while((i%j)!=0 && (j<=rt)) j++;

                if(j>rt){
                        printf("%d",i);
                        return 0;
                }
        }
}


// AtCoder165 C

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include <memory.h>
#include <malloc.h>
#include <stdlib.h>

// qsortで用いる比較用関数．*a<*bならaが先になる．
int compare(const void* a, const void* b) {
    return *(int*)a - *(int*)b;
}

int revcompare(const void* a, const void* b) {
    return *(int*)b- *(int*)a;
}

struct node_t{
    int value;
    struct node_t* left;
    struct node_t* right;
};

struct node_t* mallocNode(int adds) {
    struct node_t* add;

    add = (struct node_t*)malloc(sizeof(struct node_t));
    if (add == NULL) {
        return NULL;
    }

    add->left = NULL;
    add->right = NULL;
    add->value =  adds;

    return add;
}

int addNode(struct node_t* root, int tmps) {
    struct node_t* node;
    if (root == NULL) {
        root = mallocNode(tmps);
        return 0;
    }

    node = root;
    while (1) {
        if (tmps < node->value) {
            if (node->left == NULL) {
                node->left = mallocNode(tmps);
                return 0;
            }
            node = node->left;
        }
        else if (tmps > node->value) {
            if (node->right == NULL) {
                node->right = mallocNode(tmps);
                return 0;
            }
            node = node->right;
        }
        else {
            return 1; // 重複のときのみ1を返す
        }
    }

}

int main() {
    int i,j;
    int n;
    int x;

    scanf("%d", &x);

    for(i=x;;i++){
        for(j=2;j<=i;j++){
            if(i%j == 0) break;
        }
        //printf("i:%d j:%d\n", i, j);
        if(i==j) break;
    }
    printf("%d", i);
    return 0;

}


#include <stdio.h>

int main()
{
	int X;
	scanf("%d", &X);

	int i, x;
	for (x = X; x <= X * 2; x++) {
		for (i = 2; i * i <= x; i++) {
			if (x % i == 0) break;
		}
		if (i * i > x) break;
	}

	printf("%d\n", x);
	fflush(stdout);
	return 0;
}


#include<stdio.h>
int main()
{
long long int x;
scanf("%lld",&x);
bool s = true;
while(s)
{
  int t = 1;
  for(int i = 2;i<=x;i++)
    if(x%i == 0)
    {
      x++;
      t = 0;
      break;
    }
  if (t==0)
  {
    printf("%lld",x);
    s = false;
  }
}
}


#include<stdio.h>

int main()
{

    int a,b,c,i,j,k;
    int flag=0;
    scanf("%d",&a);
    i=a;
    while(i>=a)
    {

        for(j=2;j<=10;j++)
        {

            if(i%j==0 && j!=i)
            {
                flag=1;
                break;
            }
        }
        if(flag==0)
        {

            b=i;
            break;
        }
        i++;
    }
    printf("%d",i);
}


#include<stdio.h>
int main ()
{
    int x,i,j,flag;
    scanf("%d", &x);
    for(i=x; i<x+100; i++){
        flag=0;
        for(j=2; j<=i/2; j++){
            if(i%j==0)
            {flag=1;
             break;}
    }
    if(flag==0){break;}
    }
    printf("%d", i);


var fs = require('fs');
var inn = parseInt(fs.readFileSync(0).toString());
function isPrime(n) {
    if(n <= 3) return n > 1;
    else if (n % 2 === 0 || n % 3 === 0) return false;
    var i = 5;
    while (Math.pow(i, 2) <= n) {
        if (n % i === 0 || n % (i + 2) === 0) return false;
        i += 6;
    }
    return true;
}
while (!isPrime(inn)) {
inn++;
}
console.log(inn);


function Main(input) {
	var lines = input.split("\n");
	var words = lines[0].split(" ");
	var x = Number(words[0]);
	while(1) {
		var cand = x++
		if(isPrime(cand)){
			console.log(cand)
			return
		}
	}
	function isPrime(num) {
		for(var d = 2; d < num; d++) {
			if(num % d === 0) {
				return false
			}
		}
		return true
	}
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"))


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	tmp = input[0].split(" ");

	var num = parseInt(tmp[0], 10);
    while(!isPrime(num)) {
        num++
    }
    console.log(num)
}
function isPrime(num) {
    for(var i = 2; i < num; i++)
      if(num % i === 0) return false;
    return num;
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function nextPrime(n){
  if(n<2)return 2;
  if(n%2===0) n=n-1;
  for(let i =n;i=i+2;){
    if(isPrime(i)) return i;
  }

  function isPrime(num){

    if(num == 2){
        return true;
    }else if(num % 2 == 0){
        return false;
    }
    var squareRoot = Math.sqrt(num);
    for(var i = 3; i <= squareRoot; i += 2) {
      if (num % i === 0) {
         return false;
      }
    }
    return true;
}
}


function main(input) {
  if (input == 2 || input == 3) return input;

  var base = (Math.floor(input / 6)) * 6
  while (true) {
    if (isPrime(base - 1)) {
      console.log(base - 1)
      break;
    }

    if (isPrime(base + 1)) {
      console.log(base + 1)
      break;
    }
    base += 6;
  }
}
function isPrime(n) {
  for (var i = Math.floor(Math.sqrt(n)); i <= Math.floor(n / 2); i++) {
    if (n % i == 0) return false;
  }
  return true;
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input) {
  var primes = [2, 3]
  if (input == 2 || input == 3) {
    return input;
  }

  var base = 6
  while (true) {
    var root = Math.ceil(Math.sqrt(base))
    var tests = primes.filter(p => p <= root)

    var elder = base - 1
    var younger = base + 1

    if (tests.every(p => elder % p != 0)) {
      primes.push(elder);
      if (input <= elder) {
        return console.log(elder);
      }
    }
    if (tests.every(p => younger % p != 0)) {
      primes.push(younger);
      if (input <= younger) {
        return console.log(younger);
      }
    }
    base = base + 6;
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));