18. 两数积全为1

给定一个非负整数a(不超过106),是否存在整数b,使得ab的乘积全为1。如果存在,返回最小的乘积的位数。如果不存在,返回-1。

样例:a=3,存在b=37,使得3*37=111,则函数应返回3(111的位数)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication15
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(FindMinAllOne(9));
        }

        static int FindMinAllOne(int n)
        {
            if (n%2==0||n%5==0||n<0)
            {
                return -1;
            }
            if (n==1)
            {
                return 1;
            }

            int ans = 1;
            int p = 1;
            while (true)
            {
                if (p%n==0)
                {
                    return ans;
                }
                else
                {
                    p = p % n;
                    p = p * 10 + 1;
                    ans++;
                }
            }
        }
    }
}
View Code

 

posted @ 2014-02-10 14:37  Ligeance  阅读(209)  评论(0编辑  收藏  举报