Magnanimous Numbers | C ++ implementation to check if a number is Magnanimous ; Function to check if n is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to check if the number is Magnanimous or not ; converting the number to string ; finding length of string ; number should not be of single digit ; loop to find all left and right part of the string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } bool isMagnanimous ( int N ) { string s = to_string ( N ) ; int l = s . length ( ) ; if ( l < 2 ) return false ; for ( int i = 0 ; i < l - 1 ; i ++ ) { string left = s . substr ( 0 , i + 1 ) ; string right = s . substr ( i + 1 ) ; int x = stoi ( left ) ; int y = stoi ( right ) ; if ( ! isPrime ( x + y ) ) return false ; } return true ; } int main ( ) { int N = 12 ; isMagnanimous ( N ) ? cout << " Yes " : cout << " No " ; return 0 ; }